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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by