java 如何检查字符串是否具有列表中的子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27110563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if a string has a substring from a List?
提问by Swapnil Nawale
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";
String s1 has "mary" from the keywords, but string s2 does not have it. So, I would like to define a method:
字符串 s1 有关键字中的“mary”,但字符串 s2 没有。所以,我想定义一个方法:
boolean containsAKeyword(String str, List<String> keywords)
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.
哪里containsAKeyword(s1, keywords)
会返回真但containsAKeyword(s2, keywords)
会返回假。即使有单个子字符串匹配,我也可以返回 true。
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.
我知道我可以遍历关键字列表并在列表中的每个项目上调用 str.contains() ,但我想知道是否有更好的方法来遍历完整列表(避免 O(n) 复杂性)或者Java为此提供了任何内置方法。
回答by AdamMc331
I would recommend iterating over the entire list. Thankfully, you can use an enhanced for loop:
我建议遍历整个列表。幸运的是,您可以使用增强的 for 循环:
for(String listItem : myArrayList){
if(myString.contains(listItem)){
// do something.
}
}
EDITTo the best of myknowledge, 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?
编辑据我所知,您必须以某种方式迭代列表。想一想,不经过它,你怎么知道列表中包含了哪些元素呢?
EDIT 2
编辑 2
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:
我可以看到迭代快速运行的唯一方法是执行上述操作。按照这种设计方式,一旦您找到匹配项,它就会提前中断,而无需进一步搜索。您可以将 return false 语句放在循环的末尾,因为如果您检查了整个列表而没有找到匹配项,则显然没有。下面是一些更详细的代码:
public boolean containsAKeyword(String myString, List<String> keywords){
for(String keyword : keywords){
if(myString.contains(keyword)){
return true;
}
}
return false; // Never found match.
}
EDIT 3
编辑 3
If you're using Kotlin, you can do this with the any
method:
如果您使用 Kotlin,则可以使用以下any
方法执行此操作:
val containsKeyword = myArrayList.any { it.contains("keyword") }
回答by fdam
In JDK8 you can do this like:
在 JDK8 中,您可以这样做:
public static boolean hasKey(String key) {
return keywords.stream().filter(k -> key.contains(k)).collect(Collectors.toList()).size() > 0;
}
hasKey(s1); // prints TRUE
hasKey(s2); // prints FALSE
回答by Pier-Alexandre Bouchard
Iterate over the keyword list and return true
if the string contains your keyword. Return false
otherwise.
迭代关键字列表,true
如果字符串包含您的关键字,则返回。false
否则返回。
public boolean containsAKeyword(String str, List<String> keywords){
for(String k : keywords){
if(str.contains(k))
return true;
}
return false;
}
回答by Junaid
Here is the solution
这是解决方案
List<String> keywords = new ArrayList<>();
keywords.add("mary");
keywords.add("lamb");
String s1 = "mary is a good girl";
String s2 = "she likes travelling";
// The function
boolean check(String str, List<String> keywords)
Iterator<String> it = keywords.iterator();
while(it.hasNext()){
if(str.contains(it.next()))
return true;
}
return false;
}
回答by Sarthak Mittal
I think you should check the method present in the String class:
我认为您应该检查 String 类中存在的方法:
String s1 = "mary is a good girl";
if(s1.contains("mary")
{
//Success
}
If you want to improve performance maybe you can first split the sentence and then calculate the sum of all the characters[ASCII values] of each word [we will call it hashvalue] and maintain a separate bucket(maybe Array) for each of them, now when you get a keyword value, first you find its hashvalue and access that array then to make it more efficient you can compare their lengths and then match the string.
如果你想提高性能,也许你可以先拆分句子,然后计算每个单词的所有字符 [ASCII 值] 的总和 [我们称之为哈希值] 并为每个单词维护一个单独的存储桶(可能是数组),现在,当您获得关键字值时,首先找到它的哈希值并访问该数组,然后为了提高效率,您可以比较它们的长度,然后匹配字符串。
Hope that helped!
希望有所帮助!
回答by gashu
You can add all the words in keywords in a hashmap. Then you can use str.contains for string 1 and string 2 to check if keywords are available.
您可以将关键字中的所有单词添加到哈希图中。然后你可以对字符串 1 和字符串 2 使用 str.contains 来检查关键字是否可用。
回答by wisher
Depending on the size of the list, I would suggest using the matches() method of String. String.matches takes a regex argument that, with smaller lists, you could sinply build a regular expression and evaluate it:
根据列表的大小,我建议使用字符串的matches() 方法。String.matches 接受一个 regex 参数,对于较小的列表,您可以简单地构建一个正则表达式并对其进行评估:
String Str = new String("This is a test string");
System.out.println(Str.matches("(.*)test(.*)"));
This should print out "true."
这应该打印出“true”。
Or you could use java.util.regex.Pattern
.
或者你可以使用java.util.regex.Pattern
.