2013-06-12 36 views
2

我有這樣的代碼:如何使.contains搜索數組中的每個字符串?

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

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

但我想,如果只執行語句,如果「值」了所有的單詞包括在陣列中,類似「你是哪裏人?」。目前,如果值只有數組中的其中一個單詞,那麼該語句將被執行。

我可以用if (value.contains("where") && value.contains("you") && value.contains ("from"))來做到這一點,但這似乎不必要的長。必須有一個使用我缺少的數組的解決方法。

那是什麼?

對不起,因爲語法不好。我患有睡眠不足。

回答

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 
+0

這是很好的和簡單的,但我覺得我們至少應該跳出循環,如果沒有額外的工作需要要做。 – Zong

+0

@宗正立好呼!我已經添加了這個優化。 – mattgmg1990

+0

完美。謝謝! –

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,那麼會丟失一個,你的方法不會執行。

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 
+1

我認爲這是最好的方法。如果它在C#中,甚至可以將它放入擴展方法中。 – Zong

+1

看起來不錯,但如果test爲null,那麼你應該立即在'for'之前返回false。同樣如果'strings.length == 0' –

+0

是。顯然,我忽略了這些細節,作爲讀者的練習 –