Borrar filtros
Borrar filtros

how o count he number of occurences of a string in an external text file?

5 visualizaciones (últimos 30 días)
I would like to count he number of occurences that the string 'ALG' has, considering an external text file and one occurence per line.
For instance, if my text file has 7 lines with the string 'ALG' (among other things), the variable c should be 7.
Right now , the code that I have is this:
n=130 %(number of lines of txt file)
fid=fopen('C:\fer\a.txt','r')
for I = 1:n
s=char(fid(I));
k = strncmp(s,'ALG',3);
However, at the line "s=char(fid(I));" I am getting the following error:
Index exceeds the number of array elements (1).
I am using MATLAB 2018b
Any help is appreciated,
Thank you,
Hugo

Respuesta aceptada

Star Strider
Star Strider el 25 de Sept. de 2020
The function you want is probably fgetl (or related functions) rather than char.
Then try:
s = fgetl(fid);
There are likely a few other ways to solve this.
In any event, fopen generates one file identifier, so subscripting it will throw that error.
If you are not already doing it, summing ‘k’ in each iteration will count the occurrences.
When you have read the file, remember to include:
fclose(fid);
to close the file.

Más respuestas (0)

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by