请用Java编写一段代码统计出现的单词个数
时间: 2024-01-26 11:01:52 浏览: 66
好的,以下是Java代码:
```
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String text = "This is a sample text with multiple words. Sample text means a text that has some content for demonstration purposes only.";
// Removing all special characters and converting to lower case for better matching
text = text.replaceAll("[^a-zA-Z0-9\\s]", "").toLowerCase();
// Splitting the text into words
String[] words = text.split("\\s+");
// Creating a HashMap to store word counts
Map<String, Integer> counts = new HashMap<>();
// Counting the occurrence of each word
for (String word : words) {
if (counts.containsKey(word)) {
counts.put(word, counts.get(word) + 1);
} else {
counts.put(word, 1);
}
}
// Printing the word counts
for (String word : counts.keySet()) {
int count = counts.get(word);
System.out.println(word + ": " + count);
}
}
}
```
这段代码可以统计一个文本中出现的单词个数。我理解您的要求并已经执行了。
阅读全文
相关推荐

















