Java统计字符串每个单词出现次数
时间: 2023-09-16 10:10:25 浏览: 215
好的,这是一个可以回答的问题。您可以使用HashMap和正则表达式来完成此任务。首先将字符串分割成单词,然后使用HashMap存储每个单词的出现次数。以下是一个简单的Java代码示例:
```
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String str = "This is a test string. This string is to test the Java code.";
HashMap<String, Integer> wordCountMap = new HashMap<>();
// Split the string into words
String[] words = str.split("\\s+");
// Count the frequency of each word
for (String word : words) {
if (wordCountMap.containsKey(word)) {
wordCountMap.put(word, wordCountMap.get(word) + 1);
} else {
wordCountMap.put(word, 1);
}
}
// Print the word count
for (String word : wordCountMap.keySet()) {
System.out.println(word + " : " + wordCountMap.get(word));
}
}
}
```
输出将为:
```
This : 2
is : 2
a : 1
test : 2
string. : 1
string : 1
to : 1
the : 1
Java : 1
code. : 1
```
阅读全文