2014-07-23 89 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