String as an "action word" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

String as an "action word"

Hi, What can I do to get a string as an "action word"? Let me explain it. I want give the User a decision "You want to go or wait?" Now the User should type "Go" or "wait" and the code continues with an if statement. Is it possible to do that and is it possible set more words to one action e.g. "Go", "go", "go for it" (that every word is activating the same if statement) Thank you

12th Jul 2019, 9:45 AM
Godmorgon
Godmorgon - avatar
6 Answers
+ 1
Sure, strings can be, just like other data types, compared by the == and != operator. If multiple words are supposed to trigger one action, you can chain them inside the if-condition using the OR operator (||). Usually you use a loop that asks the user to choose an option until the input matches one of the options you provided. An important operation that is especially useful here is transforming the string to lowercase, so you need to perform less comparisons (example in the code). Here is an example for such a menu, let me know if you have any questions on it: https://code.sololearn.com/cfkKvb1bDxNR/?ref=app
12th Jul 2019, 11:26 AM
Shadow
Shadow - avatar
+ 8
Thanks
13th Jul 2019, 8:57 AM
Muaz Ahmad
Muaz Ahmad - avatar
+ 7
You can use switch statement
12th Jul 2019, 11:26 AM
Muaz Ahmad
Muaz Ahmad - avatar
+ 7
But we can use char in switch
12th Jul 2019, 5:21 PM
Muaz Ahmad
Muaz Ahmad - avatar
+ 1
Muaz Ahmad, strings are not numerical values and therefore do not work in switch statements. You need to use an if - else if - else statement.
12th Jul 2019, 11:32 AM
Shadow
Shadow - avatar
+ 1
Indeed, Muaz Ahmad, because you can convert a character to a numerical value, to be more precise, to its ASCII value. Therefore, as you pointed out, we can use characters in switch statements, but not strings, because those can not be converted to a fixed identical numerical value. And since the question was regarding strings, a switch statement would not work for this particular problem.
12th Jul 2019, 6:34 PM
Shadow
Shadow - avatar