如何知道字符串是否在Android上的数组中?

时间:2013-03-05 15:25:05

标签: java android arrays string search

大家好我在Android中编写应用程序,我不知道该怎么做才能得到我想要的东西。我现在很简单,但请帮助我!

让我们说我有一个数组:

String coco[] = { "hi", "everybody", "superman", "batman" };

我也有:

 String heroe = "superman";

现在我需要创建一个循环,方法或其他任何东西,它接受“heroe”并在数组中搜索该值(“超人”),然后如果该值存在为TRUE并且如果不存在则为FALSE。

谢谢你们。

7 个答案:

答案 0 :(得分:9)

最舒服的方法是转换数组到列表然后进行搜索。

干净,简短且富有表现力

boolean isThere = Arrays.asList(yourArray).contains("needle");

答案 1 :(得分:1)

for(int i=0;i<coco.length;i++)
{
    if(coco[i].equals(heroe))
       return true;
}

答案 2 :(得分:1)

这是一个简单的解决方案。使用可以使用.contains()方法的ArrayList会更容易。

for(int i = 0; i < coco.length; i++)
{
        if(coco[i].equals(heroe))
        {
            // a match!
            return true;
        }
}

// no match
return false;

答案 3 :(得分:1)

只需遍历数组中的值并将它们与您要查找的值进行比较

public boolean arraySearch(String[] strArray, String key) {

    for (String s : strArray) {
        if (s.equals(key)) {
            return true;
        }
    }
    return false;
}

您可以在代码中调用arraySearch(coco, heroe);来使用此功能。

或者,您可以使用Arrays类并使用:

boolean keyPresent = Arrays.asList(coco).contains(heroe);

答案 4 :(得分:1)

你可以这样做。

只需获取要搜索的变量并迭代数组并使用equals方法。

String heroe = "superman";
boolean flag = false;
for(int index = 0; index < coco.length; index++)
{
    Strin value = coco[index];
    if(heroe.equals(value))
    {
       flag = true;
    }
}

if(flag) {
   //Exist
}
else {
   //Not Exist 
}

答案 5 :(得分:1)

你可以这样做:

    for (String testcoco : coco)
    {
        if (testcoco.contains("superman"))
        {
            return true;
        }
    }
    return false;

答案 6 :(得分:0)

public boolean checkPresence(String desired)
 for(String s:coco){
    if(s.equals(desired)){
       return true
       }
    }
    return false;