Help with picking out the first and last word in a string?
이전 댓글 표시
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 :)
채택된 답변
추가 답변 (1개)
Image Analyst
2014년 12월 1일
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
Guillaume
2014년 12월 1일
Another option is to use strsplit
words = strsplit(sentence); %break each word at whitespaces
or a regular expression:
words = regexp(sentence, '\S*', 'match')
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!