Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare strings in C using a `switch` statement?

In C there is a switch construct which enables one to execute different conditional branches of code based on an test integer value, e.g.,

int a; /* Read the value of "a" from some source, e.g. user input */ switch (a) {   case 100:     // Code     break;   case 200:     // Code     break;   default:     // Code     break; } 

How is it possible to obtain the same behavior (i.e. avoid the so-called "if-else ladder") for a string value, i.e., a char *?

like image 664
Niklas Avatar asked Oct 25 '10 13:10

Niklas


People also ask

Can we compare strings using switch statement?

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String. equals method; consequently, the comparison of String objects in switch statements is case sensitive.

Can we compare string in switch case in C?

No. In C and C++ a case label can only be a constant integer expression, so you can't switch on a C-style string or a std::string value.

How can you compare two strings in C?

We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.


2 Answers

If you mean, how to write something similar to this:

// switch statement switch (string) {   case "B1":      // do something     break;   /* more case "xxx" parts */ } 

Then the canonical solution in C is to use an if-else ladder:

if (strcmp(string, "B1") == 0)  {   // do something }  else if (strcmp(string, "xxx") == 0) {   // do something else } /* more else if clauses */ else /* default: */ { } 
like image 66
Bart van Ingen Schenau Avatar answered Oct 24 '22 14:10

Bart van Ingen Schenau


If you have many cases and do not want to write a ton of strcmp() calls, you could do something like:

switch(my_hash_function(the_string)) {     case HASH_B1: ...     /* ...etc... */ } 

You just have to make sure your hash function has no collisions inside the set of possible values for the string.

like image 25
Edgar Bonet Avatar answered Oct 24 '22 13:10

Edgar Bonet