且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串是否具有列表中的子字符串?

更新时间:2023-02-23 09:37:42

我建议遍历整个列表.幸运的是,您可以使用增强的for循环:

I would recommend iterating over the entire list. Thankfully, you can use an enhanced for loop:

for(String listItem : myArrayList){
   if(myString.contains(listItem)){
      // do something.
   }
}

编辑,据我所知,您必须以某种方式迭代该列表.想一想,如何不经过检查就知道列表中包含哪些元素?

EDIT To the best of my knowledge, you have to iterate the list somehow. Think about it, how will you know which elements are contained in the list without going through it?

编辑2

我可以看到迭代快速运行的唯一方法是执行上述操作.这种设计方式将在您找到匹配项后尽早中断,而无需进行任何进一步的搜索.您可以将return false语句放在循环末尾,因为如果您检查了整个列表却没有找到匹配项,则显然没有匹配项.这是一些更详细的代码:

The only way I can see the iteration running quickly is to do the above. The way this is designed, it will break early once you've found a match, without searching any further. You can put your return false statement at the end of looping, because if you have checked the entire list without finding a match, clearly there is none. Here is some more detailed code:

public boolean containsAKeyword(String myString, List<String> keywords){
   for(String keyword : keywords){
      if(myString.contains(keyword)){
         return true;
      }
   }
   return false; // Never found match.
}

编辑3

如果您使用的是Kotlin,则可以使用any方法进行此操作:

If you're using Kotlin, you can do this with the any method:

val containsKeyword = myArrayList.any { it.contains("keyword") }