I need to check if a String object contains() various substrings and based on the results have different pieces of code execute. Currently I have a series of else if. I would like to convert it into a switch if possible. Is there a way to do this?
currently:
if (SomeString.contains("someSubString")) {
. . . do something
} else if (SomeString.contains("anotherSubString")) {
. . . do something else
} else if (SomeString.contains("yetanotherSubString")) {
. . . do something even more different
}
.
.
.
Yes, we can use a switch statement with Strings in Java. While doing so you need to keep the following points in mind. It is recommended to use String values in a switch statement if the data you are dealing with is also Strings.
You can't switch on conditions like x. contains() . Java 7 supports switch on Strings but not like you want it. Use if etc.
No you can't.
String type is available in the switch statement starting with Java 7. enum type was introduced in Java 5 and has been available in the switch statement since then.
When I have a situation like this, and really don't want to use else if
, I do something like this:
String[] cases = {"someSubString", "anotherSubString", "yetanotherSubString"};
int i;
for(i = 0; i < cases.length; i++)
if(SomeString.contains(cases[i])) break;
switch(i) {
case 0: //someSubString
System.out.println("do something");
break;
case 1: //anotherSubString
System.out.println("do something else");
break;
case 2: //yetanotherSubString
System.out.println("do something even more different");
break;
default:
System.out.println("do nothing");
}
Of course, that has a couple of downsides. For starters, if you add another strings anywhere but the end, all the indices will shift, and you have to correct for that manually. Still, I think I have used something like that once or twice and thought it makes the code more readable. Presumably, the indices had some meaning in the program, thus coupling the 0...someSubString
in a way meaningful to the problem.
You can't use a String variable in a switch, but you can use a char, maybe a specific char is diferent in all your strings?
For "someSubString", "anotherSubString" and "yetanotherSubString" you can use something like:
switch(SomeString.chatAt(0)) {
case 's':
case 'a':
case 'y':
}
But this is only valid if you know all possible values of the string and a character of a specific position is diferent on all of them.
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