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>热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短