Find the longest word in a character vector
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have to write a function that consumes a character vector in the form of a sentence and returns the longest word to in the string to the user.
I think I am on the right track but I'm stuck.
This is what I have so far.
function word = longest_word(phrase)
code = double(phrase);
i_spaces = find(code == 32);
word = char(code(1:i_spaces(1)));
for i = 1:length(i_spaces)
if (i+1) > length(i_spaces)
break
elseif length(code(i_spaces(i)+ 1:i_spaces(i)))>length(word)
word = char(code(i_spaces(i)+ 1:i_spaces(i)));
end
end
end
i_spaces is the vector containing the locations of every space in between words.
0 commentaires
Réponses (3)
Andrei Bobrov
le 7 Avr 2012
phstr = 'etetetettete fhfhfh fg fgfgf tdfhfjfkfkfk nfjfiekehdfjgjgugtltrj'
wcl = regexp(phstr,'\w*','match')
[~,ii] = max(cellfun('length',wcl))
out = wcl(ii)
0 commentaires
Walter Roberson
le 7 Avr 2012
Words do not end only with spaces; they can end with any punctuation mark. Beware the apostrophe, which might mark the end of something being quoted, or might mark the possessive form, or might mark a contraction. Beware that commas and periods do not mark the end of a "word" when the word is a number. Beware that currency signs might come before or after a number, and if immediately adjacent to the number are sometimes considered to be part of that "word".
If you know the locations of all of words and have created a canonical form of changing all non-word characters to spaces and then all runs of spaces to single spaces, then think about using diff()
2 commentaires
Walter Roberson
le 7 Avr 2012
diff(x) for a vector x, is x(2:end) - x(1:end-1), and you've learned those commands.
Humberto Lopez Franco
le 16 Juin 2018
Does anyone care to optimize it for me???
clear;clc
fprintf(2,'I can tell you the longest word in your sentence!\n');
x=input('Go ahead, say something: ','s');
TF=isletter(x);
limit=size(x);
i=1;
while i<=limit(2)
if TF(i)~=1
x(i)=' ';
i=i+1;
else
i=i+1;
end
end
answer=strsplit(x);
i=1;
limit=size(answer);
y=zeros(1,limit(2));
while i<=limit(2)
y(i)=strlength(answer(i));
i=i+1;
end
i=1;
j=2;
while i<=limit(2) && j<=limit(2)
if y(i)>=y(j)
j=j+1;
else
i=j;
j=j+1;
end
end
A=string(answer(i));
fprintf('\n\nOk, so "%s" is the longest word in your sentence with a mere %i letter(s).\n\n',A,y(i))
2 commentaires
Walter Roberson
le 16 Juin 2018
No need to loop near the beginning.
x(~isletter(x)) = ' ';
Voir également
Catégories
En savoir plus sur Whos dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!