MATLAB: Counting characters in a file

character counting

Hello,
I am doing an online course on matlab in coursera and I have come a cross a problem that seems hard for me to solve.
I need to write a function that takes the name of the text file and a paticular charater as input and then the function must count how many times the character is present in the file and return that number.
function charnum = char_counter(b,a)
fid = fopen(b,'r');
if fid < 0 || ~ischar(a) || length(a) == 0
charnum = -1;
return
end
t=0;
d=1;
while (d>0)
d = fgetl(fid);
x = strfind(d,a);
t = t + length(x);
end
charnum = t;
fclose(fid);
end
I have passed 3 out of 4 checks, following is the error that I am getting
Variable charnum has an incorrect value. When testing with ' ' your solution returned 1 which is incorrect. (75444).
I tried countin the number of " ' ' " as well and it seemed correct to,
I would like to the mistake that I am making.
Thanks
Hussain

Best Answer

Here's a demo to count the instances of a character in a text file.
This demo searches for a space character ' ' and then replaces the space characters with squares so you can visually confirm the results.
This is the simple text file I'm reading in (also attached).
Read in the file and count the empty spaces ' '
idx shows the location of spaces.
c = fileread('myTextFile.txt');
idx = c == ' ';
sum(idx)
% ans =
% 67
To search for a case insensitive character, use upper() or lower().
idx = lower(c) == 'a';
Replace the spaces with squares
cCopy = c;
cCopy(idx) = char(746); % square character
disp(cCopy)
Spaces have been replaced with squares. Number of squares = 67