switch statement using string in C [duplicate]

萝らか妹 提交于 2021-02-16 15:24:06

问题


Possible Duplicate:
C/C++: switch for non-integers
C/C++ switch case with string

I am passing a string to a function get_band(char *str) Then I am comparing the passed argument with a specific string

if(strcmp(str, "auto"))
{
  //do something
}

My question is - since i have many number of strings to compare, how can i use switch statement instead of if/else, since switch statement supports only integral type.


回答1:


Short answer: you can't.

Long answer: this question is a duplicate of C/C++ switch case with string.




回答2:


You could do:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *words[] = {"one", "two", "four"}; // words is an array of pointers to char

void f(char *str);

int main(void) {
    f("two");
    return 0;
}

void f(char *str) {

    int i;
    for (i = 0; i < sizeof words/sizeof words[0]; i++) {
        if (!strcmp(str, words[i])) {
            /* Do something */
        }
    }
}



回答3:


No, switch only works for integers.

If you want to optimize, you can use some data structure to determine if the string is any of the known strings. For example:

  • hash table
  • trie
  • some self-balancing binary search tree, like AVL tree or red-black tree

To make use of such a data structure, assign each known string a constant integer (e.g. define or enum); given a string, you can use the data structure to map it to some number of a known string (possibly with some number meaning "unknown"). Then you can use a switch on this number and do whatever you want for each case.

You can find an existing implementation of any of the above, but if you're new to C, it might be beneficial to implement it yourself.




回答4:


A switch statement branches based on evaluating the following expression.

In your case, strcmp only promises to return less than zero, zero, or greater than zero. Even if you assume that means -1, 0, and 1 (respectively), that would mean you would only have 3 values you could choose from in your switch cases. [And that is not a safe assumption, by the way ...]

Instead, if your strings are taken from a closed set of strings (i.e. can only have one of set of values), you could tokenize the string. There are actually programs to do this for you, i.e. turns strings into tokens. (See flex(1).) This would mean that each string you expected would have some unique value, and you could switch on that value.

If this is too much trouble, just use the method you used in your question, i.e.:

if (strcmp("some string", str) == 0) {
   // handle some string
} else if strcmp("some other string", str) == 0) {
   // handle alternate case here

...

} else {
   // handle error/default case here
}



回答5:


Consider changing the logic of your program to use enums instead of strings. You can then use an array look up to map the integer enums to the corresponding string for display and logging purposes. The other options including hash etc have been covered.




回答6:


The switch statement in C / C++ accepts only three case types : integers, characters and enumerated data types (which is effectively another way of saying integer). Characters also reduce to integers when evaluated as ascii codes.

@Nikolai N Fetissov made a good suggestion : switch on a hash of the string :

#define hashOfString1 <integer hash goes here>
#define hashOfString2 <integer hash goes here>
#define hashOfString3 <integer hash goes here>

. . .

switch (hashMyString("MyString")) {
  case hashOfString1:
    /* do this */
    break;
  case hashOfString2:
    /* do that */
    break;
  case hashOfString3:
    /* do other */
    break;
  default:
    /* default behavior */
    break;
}


来源:https://stackoverflow.com/questions/8303238/switch-statement-using-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!