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

6 visualizzazioni (ultimi 30 giorni)
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)

Risposte (1)

David Fletcher
David Fletcher il 9 Apr 2018
Modificato: David Fletcher il 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 Commenti
David Fletcher
David Fletcher il 13 Lug 2021
Modificato: David Fletcher il 13 Lug 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 il 13 Lug 2021
Modificato: David Fletcher il 13 Lug 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)

Accedi per commentare.

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by