Hi, what could be the error in this program?

2 vues (au cours des 30 derniers jours)
Marj Monique Cabical
Marj Monique Cabical le 23 Avr 2021
Commenté : Walter Roberson le 24 Avr 2021
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 commentaires
Marj Monique Cabical
Marj Monique Cabical le 24 Avr 2021
Can you please suggest another code too?
Walter Roberson
Walter Roberson le 24 Avr 2021
You are expected to write longestword yourself.
Be careful about longestword compared to longest_word

Connectez-vous pour commenter.

Réponses (1)

Jan
Jan le 23 Avr 2021
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?

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by