Beginner - last word of phrase (if only one word)
Show older comments
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
per isakson
on 15 Feb 2014
Edited: per isakson
on 15 Feb 2014
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
Michael
on 15 Feb 2014
per isakson
on 15 Feb 2014
"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
Michael
on 15 Feb 2014
per isakson
on 15 Feb 2014
Answers (1)
Image Analyst
on 15 Feb 2014
0 votes
Michael: I already told you how in your last question: http://www.mathworks.com/matlabcentral/answers/116081#comment_196241
1 Comment
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
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!