如何检查字符串是否具有列表中的子字符串? [英] How can I check if a string has a substring from a List?

查看:111
本文介绍了如何检查字符串是否具有列表中的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找检查字符串是否包含关键字列表中的子字符串的最佳方法.

I am looking for the best way to check if a string contains a substring from a list of keywords.

例如,我创建一个像这样的列表:

For example, I create a list like this:

List<String> keywords = new ArrayList<>();
keywords.add("mary");
keywords.add("lamb");

String s1 = "mary is a good girl";
String s2 = "she likes travelling";

字符串s1的关键字中有"mary",但字符串s2没有.因此,我想定义一个方法:

String s1 has "mary" from the keywords, but string s2 does not have it. So, I would like to define a method:

boolean containsAKeyword(String str, List<String> keywords)

containsAKeyword(s1, keywords)将返回true,而containsAKeyword(s2, keywords)将返回false.即使只有一个子字符串匹配,我也可以返回true.

Where containsAKeyword(s1, keywords) would return true but containsAKeyword(s2, keywords) would return false. I can return true even if there is a single substring match.

我知道我可以遍历关键字列表并在列表中的每个项目上调用str.contains(),但是我想知道是否有更好的方法可以遍历整个列表(避免O(n)复杂性),或者Java是否为此提供了任何内置方法.

I know I can just iterate over the keywords list and call str.contains() on each item in the list, but I was wondering if there is a better way to iterate over the complete list (avoid O(n) complexity) or if Java provides any built-in methods for this.

推荐答案

我建议遍历整个列表.幸运的是,您可以使用增强的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") }

这篇关于如何检查字符串是否具有列表中的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆