+ 1
Is there an equivalent of the switch function, but for strings?
The usual is, you insert an integer, and one of the cases is executed depending on the integer, is there a similar function but instead of an integer i can insert a string?
4 Answers
+ 6
With strings you'd use if-else if-else along with strcmp(str1, str2)==0 (case sensitive)
Where each if or else if would be similar to a case and the else block would be similar to default. Note that, of course, there is no use of a break statement here nor will there be any fall through to the next case.
char str[] = "Hello";
if (strcmp(str, "hello")==0) {
... // not a match
} else if (strcmp(str, "heLLo")==0) {
... // not a match
} else if (strcmp(str, "hEllO")==0) {
... // not a match
} else if (strcmp(str, "Hello")==0) {
... // match
} else {
... // default
}
https://www.programiz.com/c-programming/library-function/string.h/strcmp
+ 4
FWIW... If you've not been exposed to other languages yet, switch is much more flexible in other languages.
+ 3
I wrote a code, but in the meantime they answered you. I post it the same.
edit: maybe it's worth to tell you that in case the compared strings are identical, strcmp returns 0. So the if( !strcmp ) is entered only if the strings match.
https://code.sololearn.com/cDzxGwSIb40n/?ref=app