Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use wildcards in a switch statement?

I have a switch statement that uses a string of 3 letters. For many cases (but not all) I only want to concern myself with the first 2 letters.

Example, I want every code that begins with "FF" to be handled the same:

switch(code)
{
   case "FF(?)":
      // Handle it
      break;
   default:
      break;
}

What can I do here? Can I utilize a wildcard? Do I have to consider every FF code?

For obvious reasons, I don't want to have code like this, that can grow really large:

case "FFA":
case "FFB":
case "FFD":
    // Handle it
like image 551
AdamMc331 Avatar asked Sep 19 '14 19:09

AdamMc331


People also ask

How do you use wildcards in strings?

Wildcards (*,?,~) can be used in conditions to represent one or more characters. The & character is used to concatenate, or join, two or more strings or the contents of referenced cells. Some examples of the use of the concatenation operator are: "Abc"&"Def" returns "AbcDef".

Can you use switch statement with INT?

1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed. 2) All the statements following a matching case execute until a break statement is reached.

What is a switch statement in C?

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier.


2 Answers

Do your first 2 chars at the switch, not at case.

Use the default case to then fall back to three letter cases. It's not the cleanest, but it would work. Sometimes if statements are the way to go if switches don't cut it.

switch(code.Substring(0, 2))
{
    case "FF":
       ...
    default:
        switch(code)
        {
            case "ABC":
                ....
        }
}
like image 164
Nathan A Avatar answered Oct 06 '22 18:10

Nathan A


Use if then else for these kinds of comparisons. Reserve your switch case statements for cases that are readily identifiable as discrete values.

like image 28
Robert Harvey Avatar answered Oct 06 '22 19:10

Robert Harvey