我想使用 Java 快速有效地查找某个单词在字符串中出现的次数。
单词之间用空格分隔,我正在寻找完整的单词。
Example:
string: "the colored port should be black or white or brown"
word: "or"
output: 2
对于上面的例子,“colored”和“port”不被计算在内,但“or”被计算在内。
我考虑使用 substring() 和 contains() 并迭代字符串。但接下来我们需要检查周围的空间,我认为这效率不高。而且 StringUtils.countMatches() 效率不高。
我尝试的最好方法是在空格上分割字符串并迭代单词,然后将它们与给定的单词进行匹配:
String string = "the colored port should be black or white or brown";
String[] words = string.split(" ");
String word = "or";
int occurrences = 0;
for (int i=0; i<words.length; i++)
if (words[i].equals(word))
occurrences++;
System.out.println(occurrences);
但我期待使用匹配器和正则表达式的有效方法。
所以我测试了以下代码:
String string1 = "the colored port should be black or white or brown or";
//String string2 = "the color port should be black or white or brown or";
String word = "or";
Pattern pattern = Pattern.compile("\\s(" + word + ")|\\s(" + word + ")|(" + word + ")\\s");
Matcher matcher = pattern.matcher(string1);
//Matcher matcher = pattern.matcher(string2);
int count = 0;
while (matcher.find()){
match=matcher.group();
count++;
}
System.out.println("The word \"" + word + "\" is mentioned " + count + " times.");
它应该足够快,并且为我提供了 string1 的正确答案,但不是 string2 (已注释)。正则表达式似乎需要一些更改。
有什么想法吗?
最佳答案
我试验并评估了三个答案;基于分割和基于匹配器(如问题中所述),以及基于Collections.Frequency()(如@上面的评论中所述) 4城堡)。每次我测量循环重复1000万次的总时间。因此,基于拆分的答案往往是最有效的方式:
String string = "the colored port should be black or white or brown";
String[] words = string.split(" ");
String word = "or";
int occurrences = 0;
for (int i=0; i<words.length; i++)
if (words[i].equals(word))
occurrences++;
System.out.println(occurrences);
然后是基于 Collections.Frequency() 的答案,运行时间稍长(大约慢 5%):
String string = "the colored port should be black or white or brown or";
String word = "or";
int count = Collections.frequency(Arrays.asList(string.split(" ")), word);
System.out.println("The word \"" + word + "\" is mentioned " + count + " times.");
基于匹配器的解决方案(问题中提到)要慢得多(运行时间大约是原来的 5 倍)。
关于java - 使用Java快速计算字符串中单词出现次数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971941/