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

14 views (last 30 days)
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)

Answers (1)

David Fletcher
David Fletcher on 9 Apr 2018
Edited: David Fletcher on 9 Apr 2018
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 Comments
David Fletcher
David Fletcher on 13 Jul 2021
Edited: David Fletcher on 13 Jul 2021
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 on 13 Jul 2021
Edited: David Fletcher on 13 Jul 2021
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)

Sign in to comment.

Categories

Find more on Desktop 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!