代码之家  ›  专栏  ›  技术社区  ›  Alisa

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

  •  2
  • Alisa  · 技术社区  · 8 年前

    我希望使用Java以快速高效的方式查找单词在字符串中出现的次数。

    单词用空格隔开,我正在寻找完整的单词。

    Example: 
    string: "the colored port should be black or white or brown"
    word: "or"
    output: 2
    

    对于上述示例,“有色”和“端口”不计算在内,但“或”被计算在内。

    我考虑过使用 子串() 包含() 并在字符串上迭代。但是,我们需要检查周围的空间,我认为这不是有效的。而且 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没有(注释)。似乎需要对正则表达式进行一点修改。

    有什么想法吗?

    3 回复  |  直到 8 年前
        1
  •  1
  •   Alisa    8 年前

    我实验并评估了三个答案; 基于拆分 基于匹配器 (如问题所述),以及 Collections.frequency() 基于(如@4castle在上面的评论中所述)。每次我测量循环中的总时间,重复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倍)。

        2
  •  0
  •   Amit Kumar    8 年前
    public class Test {
    public static void main(String[] args) {
        String str= "the colored port should be black or white or brown";
        Pattern pattern = Pattern.compile(" or ");
        Matcher  matcher = pattern.matcher(str);
    
        int count = 0;
        while (matcher.find())
            count++;
    
        System.out.println(count);    
    }
    

    }

        3
  •  0
  •   user2575725 user2575725    8 年前

    这个怎么样?假设 word 它不会有空间。

    string.split("\\s"+word+"\\s").length - 1;