MATLAB: ‘strcmp’ works when trying to count number of times a character occurs in a textfile but ‘findstr’ fails!

character counterhomeworkstrfind

The purpose is to find the number of times a particular character/word occurs in a multi-line text document. This code works:
function charnum=char_counter(fname,character)
charnum=0;
fid=fopen(fname,"rt");%opens file
if fid<0 || ~ischar(character) %check if file not found or character is not a char
charnum=-1;
return
end
oneline=fgets(fid);
while ischar(oneline)
for x=1:length(oneline)
%compaa=re whether 'character' and words from line are same
if strcmp(oneline(x),character)==true
charnum=charnum+1;
end
end
oneline=fgets(fid);
end
But when I am using strfind, it returns an empty array for each line? strfind works for single line sentences. why does it fail here?

Best Answer

s=strfind(oneread,character);%looking for word in each sentence
strfind() returns a list of indices in oneread where the pattern character starts. If no locations are found then strfind() returns empty.
if isempty(s==0)%checking if s has any elements

s itself can be empty, but it will never contain any 0. In the context of your code, s==0 will be an array of false values the same size as s. Checking isempty() of that would be the same as checking isempty(s)
c=c+1;
So you are counting the number of times that no matches were found in the line.
Perhaps you intended
if isempty(s)==0 %checking if s has any elements
which would be the same as
if ~isempty(s)
in which case you would at least be counting the number of lines that it was found on.
But you are supposed to be checking the count of matches, not the number of lines: if the pattern occurs more than once on the same line, then it should be counted more than once.
If you are intended to count words, then you need to be careful. Suppose you are asked to count 'the' and the text is 'The theoretical theatre theologizes thews." Then the proper answer is either zero ('The' is not 'the') or one (if case distinctions are to be ignored), but you would find four.