我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
当前回答
Arrays.asList()->然后调用contains()方法将始终有效,但搜索算法要好得多,因为不需要在数组周围创建轻量级列表包装器,这就是Arrays.as list()所做的。
public boolean findString(String[] strings, String desired){
for (String str : strings){
if (desired.equals(str)) {
return true;
}
}
return false; //if we get here… there is no desired String, return false.
}
其他回答
可以使用Arrays类对值执行二进制搜索。如果数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后对其进行搜索。
ObStupidAnswer(但我认为这里有一个教训):
enum Values {
AB, BC, CD, AE
}
try {
Values.valueOf(s);
return true;
} catch (IllegalArgumentException exc) {
return false;
}
如果你不想区分大小写
Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);
您可以直接使用Arrays.asList方法以类似的方式将其初始化为List,而不是使用快速数组初始化语法,例如:
public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");
然后您可以执行(如上所述):
STRINGS.contains("the string you want to find");
Arrays.asList()->然后调用contains()方法将始终有效,但搜索算法要好得多,因为不需要在数组周围创建轻量级列表包装器,这就是Arrays.as list()所做的。
public boolean findString(String[] strings, String desired){
for (String str : strings){
if (desired.equals(str)) {
return true;
}
}
return false; //if we get here… there is no desired String, return false.
}