Counting characters in a file

조회 수: 43 (최근 30일)
Hussain Bhavnagarwala
Hussain Bhavnagarwala 2020년 3월 28일
댓글: Walter Roberson 2022년 9월 4일
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
  댓글 수: 6
Image Analyst
Image Analyst 2020년 3월 29일
Adam, I'd put that down in the answer section so you can get credit for it. I was about to say the same thing.
Adam Danz
Adam Danz 2020년 3월 29일
Thanks, Image Analyst.

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
Adam Danz 2020년 3월 29일
편집: Adam Danz 2020년 3월 30일
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
  댓글 수: 11
Ameer Hamza
Ameer Hamza 2020년 3월 30일
The condition lower(f) == lower(a) should be carefully used. It is only valid for case-insensitive counting of characters.
Adam Danz
Adam Danz 2020년 3월 30일
편집: Adam Danz 2020년 3월 30일
OP's code shared here shows
f = lower(fileread(b));
charnum = sum(f=='a');
which indicates a case insensitive search. There's no use in doing that unless the search key is also case insensitive. But it's good to explicitly point that out for the OP.
With an empty space search, case doesn't matter since upper(' ')==lower(' ').

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Rishi Diwan
Rishi Diwan 2020년 5월 23일
function charnum = char_counter(fname,character)
fid = fopen(fname,'rt');
if fid <= 0 || ~ischar(character) || ~ischar(fname) || length(fname)==0 || length(character)==0 || isempty(fname) || isempty(character)
charnum=-1;
return;
end
c=0;
ol=fgets(fid);
while ischar(ol)
c=c+count(ol,character);
ol=fgets(fid);
end
charnum=c;
fclose(fid);
end
  댓글 수: 3
yi yang
yi yang 2022년 9월 4일
a shorter version of your code:
function charnum = char_counter(fname,character)
charnum = count(fileread(fname),character);
end
Walter Roberson
Walter Roberson 2022년 9월 4일
This turns out to be a homework assignment. The checks for file existing and for the input being a valid character are required as part of the assignment.

댓글을 달려면 로그인하십시오.


Ahsiur Rahman Nirjhar
Ahsiur Rahman Nirjhar 2020년 5월 24일
function x=char_counter(a,b)
fid=fopen(a,'rt');
if fid <0 || ~ischar(b)
s=-1;
else
s=0;
oneline=fgets(fid);
while ischar(oneline)
s=s+sum(double(oneline)==double(b));
oneline=fgets(fid);
end
fclose(fid);
end
x=s;

Mert Yalcinoz
Mert Yalcinoz 2022년 2월 1일
By looking other's people answers i have combined my code and got the result.
function charnum=char_counter(fname,character) %creating function
fid=fopen(fname,'rt');
if fid<0 || ~ischar(character) || length(character)==0 %conditions
charnum=-1;
return
end
a=0; %setting a total value for found desired string
b=fgets(fid); %for reading the first line, returns single line in a string
while ischar(b) %loop for each line
a=a+count(b,character); %summing when a character is found
b=fgets(fid); %if there is no new line, b becomes -1 and loop ends.
end
charnum=a; %setting output variable
fclose(fid);
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 2월 1일
Suppose that a valid file name is passed in, but suppose that character is not a valid character or is empty. Then you set charnum=-1 and return... without having closed the file.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Convert Image Type에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by