我有一个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.
}

其他回答

你可以用两种方法检查

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并停止循环。然后断言布尔值为真。

检查此项

String[] VALUES = new String[]{"AB", "BC", "CD", "AE"};
String s;

for (int i = 0; i < VALUES.length; i++) {
    if (VALUES[i].equals(s)) {
        // do your stuff
    } else {
        //do your stuff
    }
}

如果你不想区分大小写

Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);

在下面使用-

    String[] values = {"AB","BC","CD","AE"};
    String s = "A";
    boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));