Beginner - last word of phrase (if only one word)

2 views (last 30 days)
Michael
Michael on 15 Feb 2014
Edited: Image Analyst on 15 Feb 2014
I am required to find the last word of a phrase by typing in the command window lastWord('phrase'). To do this, my m.file is a follows.
function finalword = lastWord(line)
a = strfind(line,' ');
lastSpacePlace = a(length(a));
finalwordFirstIndex = lastSpacePlace + 1;
finalwordLastIndex = length(line);
finalword = line(finalwordFirstIndex:finalwordLastIndex); end
This took me quite a long time to figure the above out and was ecstatic when it worked, but quickly realized it wouldn't accept my inputs if the phrase was only one word. Can someone nudge me in the right direction as to how I should modify my m.file?
Any help would be appreciated, I am a beginner. Thank you.
  5 Comments
Michael
Michael on 15 Feb 2014
I'll keep trying. Yes, obviously I should do it, but I'm embarrassed to say I've spent spent most of yesterday and today tweaking this m.file until I finally am up to this point now.

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 15 Feb 2014
Michael: I already told you how in your last question: http://www.mathworks.com/matlabcentral/answers/116081#comment_196241
  1 Comment
Image Analyst
Image Analyst on 15 Feb 2014
Edited: Image Analyst on 15 Feb 2014
To determine if it's one word, do that right at the beginning.
if ~strfind(line, ' ')
% Has no space, so it's a single word.
finalword = line;
return;
end

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!