2014-07-23 88 views
0

我有一個輸入字符串,其中包含一對搜索項以在包括所有搜索項的文本中查找一行。if語句中的動態和條件

例如:

String searchTerms = "java stackoverflow conditions"; 
String [] splittedTerm = searchTerms.split(" "); 

的搜尋字詞和結締組織:

if (textLine.contains(splittedTerm[0] && textLine.contains(splittedTerm[1]) && textLine.contains(splittedTerm[2])) start=true; 

但搜索詞的數量是動態的,它ALWAYSE取決於用戶的請求......

因此,根據搜索條件的數量,是否有可能使用if語句?

+1

怎麼樣a,b,c ......他們來自哪裏? –

+0

字符串相等性未用'=='測試。聽起來像你想要一個循環。 –

+0

@ElliottFrisch似乎模擬代碼。 –

回答

1

您通過String[]需要循環,你splitiing字符串後得到: -

首先添加所有你想在一個數組進行比較的元素,然後進行迭代,並通過第一陣列和陣列返回比較來自split()。確保兩個陣列的長度相同

boolean flag=true; 
String searchTerms = "java stackoverflow conditions hello test"; 
String [] splittedTerm = searchTerms.split(" "); 

for(int i=0;i<splittedTerm.length;i++){ 

    if (!(textLine[i].equals(splittedTerm[i]))){ //textLine is the array containing String literals you want to compare. 
    flag=false; 
    } 

} 
start=flag; 
+0

謝謝!我會試試看 – Ramses

1

你可以做一個遍歷所有搜索項的循環。如果發現任何不匹配,請設置一個標誌並中斷循環。在循環下面,您可以檢查標誌,如果所有搜索條件都匹配,則仍然爲真。

boolean flag = true; 
for (String searchTerm : splittedTerm){ 
    if (!stringToSearch.contains(searchTerm) { 
     flag = false; 
     break; 
    } 
} 

if (flag) 
    all terms matched 
else 
    one or more terms did not match 
+0

謝謝。好主意。類似於mustafas解決方案 – Ramses