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

27 vues (au cours des 30 derniers jours)
Yasmin Touly
Yasmin Touly le 9 Avr 2018
Modifié(e) : David Fletcher le 13 Juil 2021
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)

Réponses (1)

David Fletcher
David Fletcher le 9 Avr 2018
Modifié(e) : David Fletcher le 9 Avr 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 commentaires
David Fletcher
David Fletcher le 13 Juil 2021
Modifié(e) : David Fletcher le 13 Juil 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 le 13 Juil 2021
Modifié(e) : David Fletcher le 13 Juil 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)

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by