在java中,我们有任何方法可以找到特定字符串是字符串数组的一部分.我可以在循环中做,我想避免.
例如
String [] array = {"AA","BB","CC" };
string x = "BB"
Run Code Online (Sandbox Code Playgroud)
我想要一个
if (some condition to tell whether x is part of array) {
do something
} else {
do soemthing
}
Run Code Online (Sandbox Code Playgroud)
ΦXo*_*a ツ 29
做类似的事情:
Arrays.asList(array).contains(x);
Run Code Online (Sandbox Code Playgroud)
因为如果字符串x存在于数组中(现在转换为列表...),则返回true
if(Arrays.asList(array).contains(x)){
// is present ... :)
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用Apache提供的commons-lang库,它提供了非常受欢迎的方法contains.
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}
Run Code Online (Sandbox Code Playgroud)
此代码将为您工作:
bool count = false;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(x))
{
count = true;
break;
}
}
if(count)
{
//do some other thing
}
else
{
//do some other thing
}
Run Code Online (Sandbox Code Playgroud)