i am trying to use switch case
instead of If Else
statement, in which i have to first check length of string and as per that i have to make cases of it.
switch (mystring.length)
{
case <=25:
{
//do this
break;
}
case <50:
{
//do this
break;
}
default:
break;
}
This is some thing i want to do but unable to get how to put <25
in front of case because it is not appropriate as per switch case rules.
A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).
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. 3) The default block can be placed anywhere.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed.
The switch case in Java works like an if-else ladder, i.e., multiple conditions can be checked at once. Switch is provided with an expression that can be a constant or literal expression that can be evaluated. The value of the expression is matched with each test case till a match is found.
Its always better to use if/else for your particular case, With switch statement you can't put conditions in the case. It looks like you are checking for ranges and if the range is constant then you can try the following (if you want to use switch statement).
int Length = mystring.Length;
int range = (Length - 1) / 25;
switch (range)
{
case 0:
Console.WriteLine("Range between 0 to 25");
break;
case 1:
Console.WriteLine("Range between 26 to 50");
break;
case 2:
Console.WriteLine("Range between 51 to 75");
break;
}
This really doesn't help the OP much, but hopefully it will help someone looking for this in the future.
If you're using C# 7 (Available in Visual Studio 2017), you can switch
on a range.
Example:
switch (mystring.length)
{
case int n when (n >= 0 && n <= 25):
//do this
break;
case int n when (n >= 26 && n <= 50 ):
//do this
break;
}
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