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

49 views (last 30 days)
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 :)

Accepted Answer

Guillaume
Guillaume on 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 Comment
Guillaume
Guillaume on 30 Nov 2014
Edited: Guillaume on 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

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 1 Dec 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 Comment
Guillaume
Guillaume on 1 Dec 2014
Another option is to use strsplit
words = strsplit(sentence); %break each word at whitespaces
or a regular expression:
words = regexp(sentence, '\S*', 'match')

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!