我有一个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));
其他回答
如果你不想区分大小写
Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);
最短解数组VALUES可能包含重复项自Java 9以来
List.of(VALUES).contains(s);
如果数组未排序,则必须遍历所有内容,并对每个内容调用equals。
如果数组已排序,则可以执行二进制搜索,Arrays类中有一个。
一般来说,如果要进行大量的成员身份检查,您可能希望将所有内容存储在集合中,而不是存储在数组中。
你可以用两种方法检查
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));
}
创建初始设置为false的布尔值。运行一个循环来检查数组中的每个值,并与要检查的值进行比较。如果找到匹配项,请将布尔值设置为true并停止循环。然后断言布尔值为真。