Java如何计算字符串中出现的单词?

package org.nhooo.example.commons.lang;

import org.apache.commons.lang3.StringUtils;

public class WordCountDemo {
    public static void main(String[] args) {
        // 我们有要搜索的源文本。
        String source = "From the download page, you can download the Java " +
            "Tutorials for browsing offline. Or you can just download " +
            "the example.";
        // 我们要计算其出现次数的单词
        String word = "you";

        // 使用StringUtils.countMatches()方法,我们可以计算出现的次数
        // 给予者字符串中单词/字母的频率。
        int wordFound = StringUtils.countMatches(source, word);

        // 打印我们找到多少个单词
        System.out.println(wordFound + " occurrences of the word '" + word +
            "' was found in the text.");
    }
}

这是上面代码的结果。

2 occurrences of the word 'you' was found in the text.

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Maven中央