java - 使用Java快速计算字符串中单词出现次数的方法

标签 java regex find-occurrences

我想使用 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/

相关文章:

java - 尝试将 XML 映射到 POJO 时出现 "unexpected element"

regex - .NET 框架升级后 RegEx.Split 中的行为发生了变化

r - 如何使用R从具有多列的数据框中计算(共)发生矩阵?

java - 在 Spring MVC/JSP/Controller 中从列表框中获取用户的选择

java - 如何强制 Class.forName 仅查看 jar 内部?

java - .gif 图像在将其添加到 JTabbedpane 时不会移动

JavaScript 正则表达式替换

python - 正则表达式在python中查找部分匹配的特殊字符

java - 使用 Collections 或我的函数计算 ArrayList 中对象的出现次数

javascript - 了解查找众数的函数