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

7 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2020-9-25
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by