我有一个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的好方法?
当前回答
你可以用两种方法检查
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));
}
其他回答
在下面使用-
String[] values = {"AB","BC","CD","AE"};
String s = "A";
boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));
可以使用Arrays类对值执行二进制搜索。如果数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后对其进行搜索。
开发人员通常会:
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
上面的代码可以工作,但不需要先将列表转换为set。将列表转换为集合需要额外的时间。它可以简单到:
Arrays.asList(arr).contains(targetValue);
or
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
第一个比第二个更可读。
最短解数组VALUES可能包含重复项自Java 9以来
List.of(VALUES).contains(s);
使用Array.BinarySearch(Array,obj)查找数组中的给定对象。
例子:
if (Array.BinarySearch(str, i) > -1)` → true --exists
false--不存在