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

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

Add
line = strtrim( line );
as the first line of the function to get rid of space characters at the beginning and end of the character string. Next use
isempty( a )
in a test
adding that seems to yield the same error as before "
>> lastWord('fasdf')
_Attempted to access a(0); index must be a positive integer or logical.
Error in lastWord (line 4) lastSpacePlace = a(length(a));_
"I am required " make me think this is an exercise that you should do.
If a is empty
a(length(a));
will cause this error. Thus you must avoid that line when a is empty.
BTW: there is a compact solution with the function regexp
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)

Michael: I already told you how in your last question: http://www.mathworks.com/matlabcentral/answers/116081#comment_196241

1 Comment

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

Asked:

on 15 Feb 2014

Edited:

on 15 Feb 2014

Community Treasure Hunt

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

Start Hunting!