String as switch case/expression | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

String as switch case/expression

I try to build a code where I want to use a string variable as expression for a switch loop. Just simple strings, e.g."+" or "-". But the compiler had an error, telling me that I had to use integer for switch expression and case. Is this true or is there some trick so I can use strings instead of integer values? I just have some complicated ideas how to solve that problem...

27th Dec 2018, 7:28 PM
Dr. Raphael Haas
Dr. Raphael Haas - avatar
1 Answer
+ 2
Yes it isnt possible, and yes there are some tricks. First using an array and populate them with the input. Once user sumbit the input find which index that input belong to and use that index for the switch. Or if you dont want to bother to write a search function. You can use map with string as its key and char or int as its value. Simply use mymap[userinput] for the switch. But we cant use default here so we need a bit of if else to find out if the input is in the map or not. I have a working example if you want to look at
27th Dec 2018, 9:09 PM
Taste
Taste - avatar