Hi, what could be the error in this program?

조회 수: 2 (최근 30일)
Marj Monique Cabical
Marj Monique Cabical 2021년 4월 23일
댓글: Walter Roberson 2021년 4월 24일
Write a function named longestword that is use to compare words from the string vector named as word. The user will input the string vector word and the function will return the value of variable longest, the word with the most number of characters (and the first in the list when they have the same length).
Sampla output:
>>>longestword("Heat","Lakers","Warriors")
Warriors
Note: The following are the matlab functions that you can use in your script:
length=use to return the number of elements in a string vector.
strength=use to return the number of characters in string.
Function:
% Use if-elseif-else statement
longestword=longest_word(word)
code=double(phrase)
i_space=find(code==32)
word=char(code(1:i_spaces(1)))
for i=1:length(i_spaces)
if (1+1)>length(i_spaces)
break
elseif length(code(i_spaces(i)+1:i_spaces(1)))>length(word)
word=char(code(i_spaces(i)+1:i_spaces(1)));
end
end
Code to call you function:
word=["cent", "centennial","century"];
longestword(word)
word=["love", "care","joy"];
longestword(word)
  댓글 수: 8
Marj Monique Cabical
Marj Monique Cabical 2021년 4월 24일
Can you please suggest another code too?
Walter Roberson
Walter Roberson 2021년 4월 24일
You are expected to write longestword yourself.
Be careful about longestword compared to longest_word

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

답변 (1개)

Jan
Jan 2021년 4월 23일
Instead of converting the CHARs to doubles and searching for 32, and converting back to CHARs, you can search for the space directly:
i_space=find(word == ' ')
word = word(1:i_space(1)) % not trailing s "i_spaces"
But what happens, if the word does not contain a space? Then FIND replies the empty matrix. And if a space is found, word will contain it. You would need i_space(1)-1 instead.
In the description I find the command:
longestword("Heat","Lakers","Warriors")
This means, that a number of inputs are provided. In the code you split a string at the spaces manually. Later on you write:
word=["cent", "centennial","century"];
longestword(word)
This means, that a string array is provided. So what are the actual inputs?

카테고리

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