How to count number of words in a string

조회 수: 16 (최근 30일)
John Jamieson
John Jamieson 2020년 12월 5일
답변: Priyanka Yadav 2022년 6월 2일
My code is as follows
function [wordcount] = wordCount(strtxt, n)
wordcount=0;
y=1;
for x=1:length(strtxt)
space=strfind(strtxt, ' ');
period=strfind(strtxt, '.');
if (x+n)==space(1)
wordcount=wordcount+1;
end
if (x+n)==period
wordcount=wordcount+1;
else
wordcount=0;
end
y=y+1;
end
end
Before I explain, know that this is homework, and I'm limited to utilizing most of the built in functions involving strings that are already seen.
This question wants the function to count the number of words that have the number of letters n inside them.
This function gives me an error on x+n==space(1) (supposed to be space(y))
does anyone know how I might fix this? thanks.

답변 (2개)

Walter Roberson
Walter Roberson 2020년 12월 5일
If there are no occurences then strfind() will return empty, and an empty array cannot be indexed at (1)
English is weak on defining what a word actually is . As a result, there are linguistic "words" in English that include space characters, or include dashes, or include apostrophe, or that include commas, or that include periods, or that include digits... and sometimes other symbols.
  댓글 수: 1
John Jamieson
John Jamieson 2020년 12월 6일
For this, a word would include no spaces or punctuation. So per say, if the function recieved the string "Hi I am matt." and the parameter n was equal to two, the output would be two since Hi and am are both two letter words.

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


Priyanka Yadav
Priyanka Yadav 2022년 6월 2일
function [wordcount] = wordCount(strtxt, n) wordcount=0; y=1; for x=1:length(strtxt) space=strfind(strtxt, ' '); period=strfind(strtxt, '.'); if (x+n)==space(1) wordcount=wordcount+1; end if (x+n)==period wordcount=wordcount+1; else wordcount=0; end y=y+1; end end

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by