필터 지우기
필터 지우기

Can I use logical indexing to find how many times a character is in a string?

조회 수: 5 (최근 30일)
Hi,
I was working on a problem in this MOOC course where I had to count the number of times a character was present in a text file.
While solving the problem, I used a while loop to read each line and just added the length of the array(after using strfind)
like so:
line = fgets(fid);
sum=0;
while ischar(line)
found_in_line = length(strfind(line,character));
sum = sum + found_in_line;
line=fgets(fid);
end
But I tried to just make a sum of a logical array using logical indexing
Like so:
found_in_line = sum(contains(line,character));
But what contains does is just return true if its found in the entire string, I even tried using contains(line(1:end),character)) but this also returns only one logical answer.
Is there a method that I am not aware of which can create a logical array of a character found in a String??
Thank you!

채택된 답변

Stephen23
Stephen23 2021년 2월 2일
편집: Stephen23 2021년 2월 2일
You can perform logical comparisons on a character array (they are not very different from numeric arrays):
str = 'some random text';
nnz(str=='o') % how many 'o' characters
ans = 2
Knowing how to work with arrays is a very powerful approach to using MATLAB.
  댓글 수: 2
Mayank Mohan Arora
Mayank Mohan Arora 2021년 2월 2일
ohhhh yesss lmaooo i totally forgot the single quotes xD
thank you!
Stephen23
Stephen23 2021년 2월 2일
Strings are a container array which have character arrays inside. Hence if you want to deal with individual characters, you need to process the character arrays.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by