有没有办法将 switch 与 String.contains("") 集成? [英] is there a way to integrate a switch with String.contains("")?
问题描述
我需要检查 String 对象是否包含 () 各种子字符串,并根据结果执行不同的代码段.目前我有一系列 else if.如果可能,我想将其转换为开关.有没有办法做到这一点?
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?
目前:
if (SomeString.contains("someSubString")) {
. . . do something
} else if (SomeString.contains("anotherSubString")) {
. . . do something else
} else if (SomeString.contains("yetanotherSubString")) {
. . . do something even more different
}
.
.
.
推荐答案
当我遇到这样的情况,实在不想用else if
时,我会这样做:
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");
}
当然,这有几个缺点.首先,如果您在除末尾之外的任何地方添加另一个字符串,所有索引都会发生变化,您必须手动进行更正.尽管如此,我认为我已经使用过一两次这样的东西,并认为它使代码更具可读性.据推测,索引在程序中具有某种意义,因此以对问题有意义的方式耦合了 0...someSubString
.
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.
这篇关于有没有办法将 switch 与 String.contains("") 集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!