Best way to switch on a string in C

switch case in c programming questions
nested switch in c programming example
switch case algorithm and flowchart
while and switch in c
switch statement in c for strings
switch case alphabet in c
switch fall through c
switch statement accepts in c

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 *?

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: */
{
}

Switch statement with strings?, switch (choice[0]) { case 'f': // they chose fish break; case 'c': // they chose However, it's good to know all the options and realise how you can  Short answer: you can't. Long answer: this question is a duplicate of C/C++ switch case with string. I agree about duplication, though the linked answer specifies a hash. That's one way to tokenize strings, but not the best IMHO, unless you're ready to handle collisions (i.e. two strings hashing to the same value).

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.

C, Before we see how a switch case statement works in a C program, let's checkout the switch (variable or an integer expression) { case constant: //C Statements ; case However it is a good practice to have a default statement so that the default C - switch..case · C - goto statement · C - Arrays · 2 D array · C - String · C -  I have published a header file to perform the switch on the strings in C. It contains a set of macro that hide the call to the strcmp() (or similar) in order to mimic a switch-like behaviour. It contains a set of macro that hide the call to the strcmp() (or similar) in order to mimic a switch-like behaviour.

There is no way to do this in C. There are a lot of different approaches. Typically the simplest is to define a set of constants that represent your strings and do a look up by string on to get the constant:

#define BADKEY -1
#define A1 1
#define A2 2
#define B1 3
#define B2 4

typedef struct { char *key; int val; } t_symstruct;

static t_symstruct lookuptable[] = {
    { "A1", A1 }, { "A2", A2 }, { "B1", B1 }, { "B2", B2 }
};

#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))

int keyfromstring(char *key)
{
    int i;
    for (i=0; i < NKEYS; i++) {
        t_symstruct *sym = lookuptable[i];
        if (strcmp(sym->key, key) == 0)
            return sym->val;
    }
    return BADKEY;
}

/* ... */
switch (keyfromstring(somestring)) {
case A1: /* ... */ break;
case A2: /* ... */ break;
case B1: /* ... */ break;
case B2: /* ... */ break;
case BADKEY: /* handle failed lookup */
}

There are, of course, more efficient ways to do this. If you keep your keys sorted, you can use a binary search. You could use a hashtable too. These things change your performance at the expense of maintenance.

Can we use String in switch case?, First, I note that the C (programming language) topic was added by Quora Topic Bot rather than the How do you limit a string to be between 001 and the max string to 999 implementing conditions How can I better manage vars in Ansible​? switch is usually assumed to have nearly O(1).I'm suggesting to introduce additional level for parsing. It is known as lexical analysis. You parse you fixed set of cases to enum values and then switch as you want.

My preferred method for doing this is via a hash function (borrowed from here). This allows you to utilize the efficiency of a switch statement even when working with char *'s:

#include "stdio.h"

#define LS 5863588
#define CD 5863276
#define MKDIR 210720772860
#define PWD 193502992

const unsigned long hash(const char *str) {
    unsigned long hash = 5381;  
    int c;

    while ((c = *str++))
        hash = ((hash << 5) + hash) + c;
    return hash;
}

int main(int argc, char *argv[]) {
    char *p_command = argv[1];
    switch(hash(p_command)) {
    case LS:
        printf("Running ls...\n");
        break;
    case CD:
        printf("Running cd...\n");
        break;
    case MKDIR:
        printf("Running mkdir...\n");
        break;
    case PWD:
        printf("Running pwd...\n");
        break;
    default:
        printf("[ERROR] '%s' is not a valid command.\n", p_command);
    }
}

Of course, this approach requires that the hash values for all possible accepted char *'s are calculated in advance. I don't think this is too much of an issue; however, since the switch statement operates on fixed values regardless. A simple program can be made to pass char *'s through the hash function and output their results. These results can then be defined via macros as I have done above.

Switching on strings - C / C++, What would be the best way to switch program flow based on a string the user enters? I found out the hard way that char*'s can't be used in a  strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters. In this case there is only one delimiter. strtok returns a pointer to the character of next token. So the first time it is called, it will point to the first word. char *ptr = strtok (str, delim);

I think the best way to do this is separate the 'recognition' from the functionality:

struct stringcase { char* string; void (*func)(void); };

void funcB1();
void funcAzA();

stringcase cases [] = 
{ { "B1", funcB1 }
, { "AzA", funcAzA }
};

void myswitch( char* token ) {
  for( stringcases* pCase = cases
     ; pCase != cases + sizeof( cases ) / sizeof( cases[0] )
     ; pCase++ )
  {
    if( 0 == strcmp( pCase->string, token ) ) {
       (*pCase->func)();
       break;
    }
  }

}

C - switch statement, Each value is called a case, and the variable being switched on is checked for each switch case. Syntax. The syntax for a switch statement in C programming  Hence, we can take a maximum of 30 characters as input which is the size of the name string. To print the string, we have used puts (name);. Note: The gets () function can also be to take input from the user. However, it is removed from the C standard. It's because gets () allows you to input any length of characters.

switchcase in C Programming, By the way, the default clause inside the switch statement is optional. switch Statement Flowchart. Flowchart of switch statement. Example: Simple Calculator. //  Following is the memory presentation of the above defined string in C/C++ − Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string −

C#, Move() Method in C# with Examples · Difference between JavaScript and C Therefore, it is good to switch on strings only in cases in which the controlling data  For information on the switch expression (introduced in C# 8.0), see the article on switch expressions in the expressions and operators section. switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.

Switch Statement for Strings in C, I've hit a block when it comes to the way C handles strings. there are much better ways of handling such situations than switch statements. The replace function takes the string s, and at position 40, replaced one character, a questionmark, with the string s2. If the string is blank or you assign something out of bounds, then there's no undefined behavior. Share a link to this answer. improve this answer. edited Nov 15 at 17:54. answered Aug 19 '13 at 3:12. Eric Leschinski.

Comments
  • What do you mean by "switch on"?
  • Please reformulate so that the question makes clear what you are actually trying to do (or asking).
  • The OP probably wants to use a string as the paramater of a switch statement. As far as I know, this is not possible.
  • Actually, the problem is that I already have a switch on int and in a special case I have the value "B1" and "B2" which I want to use in same switch. The Only way is to somehow convert the "B1" and "B2" values and use them as int!!?
  • @Niklas: This is important information for your question. Can you update your question and explain (if possible with some (pseudo-)code) what you are trying to do?
  • @Niklas: You should clarify your question: how on earth could "B1" and "B2" be a special case of an int?
  • #define A 1 #define B 2 #define C S1 #define D S2 and these values are what I want to use in my switch. So simple :-)
  • @Niklas: Defines are not strings. If the define is for a number, you can use it directly in your switch like this switch (something) { case A: /*...*/ break; case B: /*...*/ break; }.
  • "make sure your hash function has no collisions inside the set of possible values for the string." -- Does such a hash function exists for the alphabet [a-zA-Z0-9_]? Any example?
  • @ArunSaha: Obviously not for arbitrary combinations of such characters.
  • If you use fixed length string keys, you can convert them each into unique integers; no collisions possible.