java统计单词出现的次数
时间: 2023-09-24 18:11:19 浏览: 36
单词出现次数
要统计Java中单词出现的次数,可以使用HashMap数据结构来记录每个单词出现的次数。具体步骤如下:
1. 将字符串转换为小写字母,方便统计单词出现的次数。
2. 使用正则表达式将字符串分割成单词数组。
3. 遍历单词数组,使用HashMap记录每个单词出现的次数。
4. 输出HashMap中每个单词出现的次数。
下面是一段示例代码:
```
public static void countWords(String text) {
// 将字符串转换为小写字母
text = text.toLowerCase();
// 使用正则表达式分割字符串成单词数组
String[] words = text.split("[^a-zA-Z]+");
// 使用HashMap记录每个单词出现的次数
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
if (word.length() > 0) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
}
// 输出每个单词出现的次数
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
```
可以调用该方法并传入需要统计的字符串,如下所示:
```
String text = "Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible.";
countWords(text);
```
输出结果如下:
```
java: 1
is: 1
a: 1
general: 1
purpose: 1
programming: 1
language: 1
that: 1
class: 1
based: 1
object: 1
oriented: 1
and: 1
designed: 1
to: 1
have: 1
as: 1
few: 1
implementation: 1
dependencies: 1
possible: 1
```
阅读全文