【问题标题】:Dynamic AND conditions in an if statementif 语句中的动态 AND 条件
【发布时间】:2014-09-14 09:41:15
【问题描述】:

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

例如:

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 语句?

【问题讨论】:

  • a,b,c ...他们来自哪里?
  • 字符串相等性未使用== 进行测试。听起来你想要一个循环。
  • @ElliottFrisch 似乎是模拟代码。
  • 您不应该使用数组而是使用列表。列表提供 contains() 方法,您可以使用该方法检查某些对象(在本例中为字符串)是否在该列表中。
  • @sᴜʀᴇsʜᴀᴛᴛᴀ 这就是为什么它是一个评论,而不是一个带有重复的 instaclose。

标签: java if-statement dynamic multiple-conditions


【解决方案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;

【讨论】:

    【解决方案2】:

    你可以做一个循环遍历所有搜索词。如果发现任何不匹配,设置一个标志并中断循环。然后,您可以在循环下方检查标志,如果它仍然是所有您的搜索词匹配。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 2016-07-22
      • 2021-04-01
      • 2018-04-12
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      相关资源
      最近更新 更多