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
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".
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.
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.
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":
....
}
}
Use if then else
for these kinds of comparisons. Reserve your switch
case
statements for cases that are readily identifiable as discrete values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With