如何使.contains搜索数组中的每个字符串?

时间:2013-06-12 20:49:26

标签: android

我有这段代码:

String[] whereyoufromarray = {"where", "you", "from"};

for (String whereyoufromstring : whereyoufromarray)
{
    if (value.contains(whereyoufromstring)) {
        //statement
    }
}

但我希望如果只执行语句,如果“value”包含数组中包含的所有单词,就像“你来自哪里?”。目前,如果value只有数组中的一个单词,则执行该语句。

我可以使用if (value.contains("where") && value.contains("you") && value.contains ("from"))执行此操作,但这似乎不必要地长。必须有一个使用我缺少的数组的解决方法。

嗯,这是什么?

p.s:抱歉语法不好。我正在遭受睡眠剥夺。

3 个答案:

答案 0 :(得分:2)

String[] whereyoufromarray = {"where", "you", "from"};

boolean valueContainsAllWordsInArray = true;
for (String whereyoufromstring : whereyoufromarray) {

    // If one word wasn't found, the search is over, break the loop
    if(!valueContainsAllWordsInArray) break;

    valueContainsAllWordsInArray = valueContainsAllWordsInArray &&
                                   value.contains(whereyoufromstring);

}

// valueContainsAllWordsInArray is now assigned to true only if value contains
// ALL strings in the array

答案 1 :(得分:2)

对于这样的情况,我通常只是为了进行测试而实现一个函数。我们称之为 containsAll()

public static boolean containsAll(String[] strings, String test)
{
    for (String str : strings)
        if (!test.contains(str))
            return false;
    return true;
}

现在你做了

if (containsAll(whereyoufromarray, value))
    //statement

答案 2 :(得分:0)

 String[] whereyoufromarray = {"where", "you", "from"};
 int arrayLength = whereyoufromarray.length;
 int itemCount = 0;
 for(String whereyoufromstring : whereyoufromarray)
 {
    if(value.contains(whereyoufromstring))
    {
        itemCount++; 
    }
 }
 if (itemCount == arrayLength){
    //do your thing here   
 }
粗略的想法。我没有我的IDE来证明这一点,但基本上你可以设置一个计数器=你已知数组的长度,然后检查数组中的每个值,看它是否包含匹配..如果它,它增加另一个计数器。最后,测试您的计数器以查看它是否与数组的长度匹配,因此在您的示例中,如果itemCount = 3,则所有值都匹配。如果它是2,那么一个将丢失,你的方法将不会执行。