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

displayMATLABscriptstringwords

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 🙂

Best Answer

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);