我有一个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的好方法?
当前回答
在下面使用-
String[] values = {"AB","BC","CD","AE"};
String s = "A";
boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));
其他回答
使用简单的循环是最有效的方法。
boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
由Programcreek提供
您可以使用Apache Commons Lang中的ArrayUtils.contains
公共静态布尔包含(Object[]数组,Object objectToFind)
注意,如果传递的数组为空,则此方法返回false。
还有一些方法可用于所有类型的基元数组。
例子:
String[] fieldsToInclude = { "id", "name", "location" };
if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
// Do some stuff.
}
你可以用两种方法检查
A) 通过将数组转换为字符串,然后通过.incontains方法检查所需的字符串
String a = Arrays.toString(VALUES);
System.out.println(a.contains("AB"));
System.out.println(a.contains("BC"));
System.out.println(a.contains("CD"));
System.out.println(a.contains("AE"));
B) 这是一种更有效的方法
Scanner s = new Scanner(System.in);
String u = s.next();
boolean d = true;
for (int i = 0; i < VAL.length; i++) {
if (VAL[i].equals(u) == d)
System.out.println(VAL[i] + " " + u + VAL[i].equals(u));
}
可以使用Arrays类对值执行二进制搜索。如果数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后对其进行搜索。
使用Array.BinarySearch(Array,obj)查找数组中的给定对象。
例子:
if (Array.BinarySearch(str, i) > -1)` → true --exists
false--不存在