Java - 在字符串数组中搜索字符串

Har*_*i M 11 java arrays

在java中,我们有任何方法可以找到特定字符串是字符串数组的一部分.我可以在循环中做,我想避免.

例如

String [] array = {"AA","BB","CC" };
string x = "BB"
Run Code Online (Sandbox Code Playgroud)

我想要一个

if (some condition to tell whether x is part of array) {
      do something
   } else {
     do soemthing
   }
Run Code Online (Sandbox Code Playgroud)

ΦXo*_*a ツ 29

做类似的事情:

Arrays.asList(array).contains(x);
Run Code Online (Sandbox Code Playgroud)

因为如果字符串x存在于数组中(现在转换为列表...),则返回true

例:

if(Arrays.asList(array).contains(x)){
    // is present ... :)
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为重要的是要注意,这并不能消除检查“数组”中的每个元素是否与“ x”匹配,而只是向程序员隐藏了这项工作。不能敲这个答案。人们应该意识到,仅此而已。 (2认同)
  • 并考虑这会创建一个ArrayList对象,仅用于搜索字符串。 (2认同)
  • 这会对性能造成影响 - 如果您担心性能 (2认同)

Art*_*eda 7

您还可以使用Apache提供的commons-lang库,它提供了非常受欢迎的方法contains.

import org.apache.commons.lang.ArrayUtils;

public class CommonsLangContainsDemo {

    public static void execute(String[] strings, String searchString) {
        if (ArrayUtils.contains(strings, searchString)) {
            System.out.println("contains.");
        } else {
            System.out.println("does not contain.");
        }
    }

    public static void main(String[] args) {
        execute(new String[] { "AA","BB","CC" }, "BB");
    }

}
Run Code Online (Sandbox Code Playgroud)


Vat*_*ura 5

此代码将为您工作:

bool count = false;
for(int i = 0; i < array.length; i++)
{
    if(array[i].equals(x))
    {
        count = true;
        break;
    }
}
if(count)
{
    //do some other thing
}
else
{
    //do some other thing
}
Run Code Online (Sandbox Code Playgroud)