how do i use the strtok() function in combination with the while loop?
14 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
回答(1 个)
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
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
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)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!