0

我有一个包含几个搜索词的输入字符串,用于在包含所有搜索词的文本中查找一行。

例如:

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

搜索词是 AND 连接的:

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

但是搜索词的数量是动态的,它总是取决于用户的请求......

那么是否有可能根据搜索词的数量使用 if 语句?

4

2 回答 2

1

您需要遍历String[]拆分字符串后得到的内容:-

首先将要比较的所有元素添加到一个数组中,然后迭代并比较第一个数组和从 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;
于 2014-07-23T09:37:28.930 回答
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
于 2014-07-23T09:23:21.883 回答