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

6 ビュー (過去 30 日間)
Hugo
Hugo 2020 年 9 月 25 日
回答済み: Star Strider 2020 年 9 月 25 日
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 Center および File ExchangeData 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