Comparing words in text file line by line

2 ビュー (過去 30 日間)
Naga
Naga 2019 年 8 月 12 日
コメント済み: Adam Danz 2019 年 8 月 13 日
I got a text file with only one word in each line. How can I open and compare each word from this file with required word in a loop?

採用された回答

Adam Danz
Adam Danz 2019 年 8 月 12 日
編集済み: Adam Danz 2019 年 8 月 12 日
"I got a text file with only one word in each line. How can I open and compare each word from this file with required word in a loop?"
It's probably best to read the entire file rather than line-by-line. Then you compare each line with your required word. Here's a demo that reads a file named "data.txt" and searches for the requiredWord "sunshine".
% Read in the entire file, keep columnar arrangement
t = strsplit(fileread('data.txt'))';
requiredWord = 'sunshine';
[hit, lineNumber] = ismember(requiredWord, t);
% If you don't want case sensitivity:
% hit = ismember(lower(requiredWord), lower(t));
If you must read line-by-line, use fgetl() in a while-loop that loops through the file line by line. This demo stops either when the word was found or the last line was read.
% Read line by line
fid = fopen('data.txt');
tline = fgetl(fid);
hit = false;
c = 0; %counter
while ischar(tline) && ~hit
c = c+1; % if you want the row number
hit = strcmp(requiredWord, tline); % use strcmpi() for case insensitivity
tline = fgetl(fid);
end
fclose(fid);
  2 件のコメント
Naga
Naga 2019 年 8 月 13 日
Thank you so much Adam Danz. It worked.
Adam Danz
Adam Danz 2019 年 8 月 13 日
Glad I could help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by