Java计算字符串单词出现次数
时间: 2023-09-20 09:09:28 浏览: 94
可以使用Java中的split()函数将字符串按空格或标点符号分成单词数组,然后用HashMap统计每个单词出现的次数。以下是示例代码:
```
import java.util.HashMap;
public class WordCount {
public static void main(String[] args) {
String str = "how much wood would a woodchuck chuck, if the woodchuck could chuck wood?";
String[] words = str.split("[\\s,\\.\\?]+"); // 按空格、逗号、句号、问号分割字符串
HashMap<String, Integer> map = new HashMap<>();
for (String word : words) {
if (word.length() > 0) { // 排除空白单词
Integer count = map.get(word);
if (count == null) {
count = 0;
}
map.put(word, count + 1);
}
}
System.out.println(map);
}
}
```
输出结果为:{if=1, chuck=2, could=1, a=2, how=1, woodchuck=2, the=1, much=1, would=1, wood=2},表示每个单词出现的次数。
阅读全文