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>热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练