Help with picking out the first and last word in a string?

20 Ansichten (letzte 30 Tage)
Chrissie
Chrissie am 30 Nov. 2014
Kommentiert: Guillaume am 1 Dez. 2014
Hi,
My code so far is:
Str=input('Give a string: ');
ind=find(Str==' ');
num_words=size(ind,2)+1;
disp('Number of blank spaces:')
disp(length(ind))
disp('Number of words in the string:')
disp(num_words)
I wanted to know how to display the first and last word from the string entered, any suggestions are appreciated :)

Akzeptierte Antwort

Guillaume
Guillaume am 30 Nov. 2014
I would use numel(ind) instead of size(ind, 2), since ind is a vector.
As for your question, the first word is the content of Str up to the first space ( ind(1)-1) and the last is the content of Str from the last space( ind(end)+1), so:
firstword = Str(1:ind(1)-1);
lastword = Str(ind(end)+1:end);
  1 Kommentar
Guillaume
Guillaume am 30 Nov. 2014
Bearbeitet: Guillaume am 30 Nov. 2014
Sounds like you're setting the field of a structure on a variable that was originally a double. This has nothing to do with the code I posted. The warning should have shown you the offending line (which would have been good to post).
The following would cause the warning:
somevar = 5; %somevar is double
somevar.somefield = 4; %somevar is now a struct

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 1 Dez. 2014
I just use John D'Errico's allwords(): http://www.mathworks.com/matlabcentral/fileexchange/27184-allwords It splits apart a string into all the different words. It's very easy to use. (It has several options for tricky strings too.)
theWords = allwords('I wanted to know how to display the first and last word')
firstWord = theWords{1} % Extract the first word into its own variable.
lastWord = theWords{end} % Extract the last word into its own variable.
In the command window you'll see:
theWords =
'I' 'wanted' 'to' 'know' 'how' 'to' 'display' 'the' 'first' 'and' 'last' 'word'
firstWord =
I
lastWord =
word
  1 Kommentar
Guillaume
Guillaume am 1 Dez. 2014
Another option is to use strsplit
words = strsplit(sentence); %break each word at whitespaces
or a regular expression:
words = regexp(sentence, '\S*', 'match')

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by