How to simplify this comparison?

4

I often fall into the following situation:

For example in C #:

string variavel= "x";

boolean b = (variavel == "a" || variavel == "d" ||.....|| variavel== "y");
  

Is there any way to simplify something like b = ("a" || "b" ||   .... "and")?

Besides being annoying, I think it will improve readability a lot if there is something similar. Switch case does not help much.

    
asked by anonymous 28.01.2016 / 18:47

3 answers

6

In C # you can do the following with LINQ :

bool b = new string[] {"a", "b", ...}.Any(s => s == variavel);

See here an example of the code .

    
29.01.2016 / 15:46
2

In C, if the strings are just characters, I'd use strchr()

char *b;
char variavel[100] = "x";
b = strchr("ad...y", *variavel);
// usa b como boolean
if (b) ok();

If the strings are actually sequences of 0 or more characters, you would opt for a sequence of if s chained

char variavel[100] = "XPTO";
if (strcmp(variavel, "AAAA") == 0) ok();
else if (strcmp(variavel, "DDDD") == 0) ok();
else if (strcmp(variavel, "....") == 0) ok();
else if (strcmp(variavel, "YYYY") == 0) ok();
    
28.01.2016 / 19:22
1

I can not think of an alternative to successive comparisons. The best thing to do would be to put each comparison on a different line as in the case below, but would only improve visibility:

bool b = (
    variavel == "a" ||
    variavel == "b" ||
    ...             ||
    variavel == "y"
)
    
29.01.2016 / 13:48