how do i use the strtok() function in combination with the while loop?

조회 수: 28 (최근 30일)
Yasmin Touly
Yasmin Touly 2018년 4월 9일
편집: David Fletcher 2021년 7월 13일
I have been trying to teach myself MATLAB for the past few weeks, and I have this one question regarding the strtok function. How do I write a matlab program that will read a sentence and then print each word on a separate line after the characters are to be converted to uppercase? Now, I am familiar with using the strtok function, but how do u use it in combination with the while loop?
s = 'Welcome to the coffee shop'
token = strtok (s)

답변 (1개)

David Fletcher
David Fletcher 2018년 4월 9일
편집: David Fletcher 2018년 4월 9일
str='Welcome to the coffee shop'
newStr=[]
while length(str)~=0
[str, remain] = strtok(str)
newStr=[newStr upper(str) 10]
str=remain
end
disp(newStr)
WELCOME
TO
THE
COFFEE
SHOP
Although, as you can see strtok() will do the job you are asking of it, in reality you probably wouldn't use strtok for this task. Instead, split() or regexp() would split the string up into separate words in a single command
  댓글 수: 3
David Fletcher
David Fletcher 2021년 7월 13일
편집: David Fletcher 2021년 7월 13일
Essentially each call to the strtok function breaks the sentence at each whitespace character and returns the preceeding word. This line:
newStr=[newStr upper(str) 10]
takes each word from strtok and concatenates them back together. The 10 in this context should not be thought of as a number but rather as a character - if you look up the character that corresponds to an ASCII value of 10 you will find that is a linefeed. So the 10 is adding a linefeed after each word so that it gets printed on a separate line. Without the 10, there will be no linefeeds so all the words will get mashed together as in WELCOMETOTHECOFFEESHOP
David Fletcher
David Fletcher 2021년 7월 13일
편집: David Fletcher 2021년 7월 13일
Maybe this equivalent bit of code makes more sense:
str='Welcome to the coffee shop'
newStr=[]
while length(str)~=0
[str, remain] = strtok(str)
newStr=[newStr upper(str) newline]
str=remain
end
disp(newStr)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by