+ 8
[Edited: Changed sample code from C to C++ and simplified the case values.] Just one of many possibilities to transform a string into a representative index. The options are all in one string. The position in the options string becomes the case value. #include <string> string options = "one two three four "; string response = "three"; switch(options.find(response)) { case 0: //one break; case 4: //two break; case 8: //three break; case 14: //four break; default: //invalid input }
21st Mar 2022, 7:08 AM
Brian
Brian - avatar
+ 4
Check this out Manav Roy[LESS ACTIVE DUE TO EXAMS] We can't use a string as the switch(variable), but you can use a hashing algorithm. https://code.sololearn.com/cyyflHwJ32OR/?ref=app
21st Mar 2022, 8:31 AM
HungryTradie
HungryTradie - avatar
+ 3
Feasible, with extra work https://learnmoderncpp.com/2020/06/01/strings-as-switch-case-labels/ But that depends on whether you find the feasibility to be worthy of the extra work.
21st Mar 2022, 7:20 AM
Ipang
+ 3
c/c++ switch cases must be of integral value. Those can't support string literals as cases. If you want to use strings as case values, then find a logic to it as a integer constant as of codes by @Brian and @HungryTradie.
21st Mar 2022, 9:16 AM
Jayakrishna 🇼🇳
+ 2
Just same as any other type. { String n = "one"; Switch(n){ case "one": System.out.println("I am num 1"); break; class "two": System.out.println("I am num 2"); break; default: System.out.println("no match"); } Check this one out: https://www.geeksforgeeks.org/string-in-switch-case-in-java/
21st Mar 2022, 7:03 AM
kev_coding
kev_coding - avatar
+ 2
Manav Roy[LESS ACTIVE DUE TO EXAMS] my sample code was in C. Now that I realized that you tagged C++ I simplified my sample to work with C++ strings. It should be easier to understand.
21st Mar 2022, 9:00 AM
Brian
Brian - avatar
+ 1
VB.Net's select/case statement has the flexibility that you crave. https://www.guru99.com/vb-net-select-case.html
21st Mar 2022, 10:26 AM
Brian
Brian - avatar
0
Manav Roy[LESS ACTIVE DUE TO EXAMS] you are looking in the wrong language. Have you tried VB.Net?
21st Mar 2022, 10:18 AM
Brian
Brian - avatar
0
Wow
22nd Mar 2022, 7:09 PM
Đ’Đ°Đ»Đ”Ń€ĐžŃ
Đ’Đ°Đ»Đ”Ń€ĐžŃ - avatar