Java统计英文句子中每个单词出现的次数
时间: 2023-11-24 20:08:22 浏览: 106
Java实现(统计一段文字中每个字出现的次数)
5星 · 资源好评率100%
可以使用Java中的HashMap来实现统计英文句子中每个单词出现的次数。具体实现步骤如下:
1. 将英文句子按照空格分隔成单词数组。
2. 遍历单词数组,使用HashMap来统计每个单词出现的次数。
3. 如果单词已经在HashMap中存在,则将该单词出现次数加1;否则,将该单词加入HashMap并将出现次数初始化为1。
下面是Java代码示例:
```java
import java.util.HashMap;
public class WordCount {
public static void main(String[] args) {
String sentence = "This is a test sentence. This sentence is used for testing.";
String[] words = sentence.split(" ");
HashMap<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
for (String word : wordCount.keySet()) {
System.out.println(word + ": " + wordCount.get(word));
}
}
}
```
输出结果为:
```
This: 2
is: 2
a: 1
test: 1
sentence.: 1
sentence: 1
used: 1
for: 1
testing.: 1
```
阅读全文