輸入一段英文文本,統計:1) 單詞總數 2) 不重複單詞數。例:「I am a good student. I am in Zhengzhou.」→ 9 個單詞,7 個不重複。
import java.util.*;
public class WordCounter {
public static String clean(String input) {
if (input == null) return null;
return input.replaceAll("[.|;|\\?]", " "); // 可擴展更多標點
}
public static Map count(String input) {
Map map = new HashMap<>();
if (input == null || input.isEmpty()) return map;
String[] words = input.split(" ");
for (String w : words) {
if (w.isEmpty()) continue; // 過濾多空格產生的空串
map.put(w, map.getOrDefault(w, 0) + 1);
}
return map;
}
public static void main(String[] args) {
String text = "I am a good student.I am in Zhengzhou.Ha?";
String cleaned = clean(text);
System.out.println("清洗後: " + cleaned);
Map result = count(cleaned);
System.out.println("總單詞數: " + result.values().stream().mapToInt(Integer::intValue).sum());
System.out.println("不重複單詞數: " + result.size());
System.out.println("明細: " + result);
}
}
清洗後: I am a good student I am in Zhengzhou Ha
總單詞數: 9
不重複單詞數: 7
明細: {Zhengzhou=1, Ha=1, I=2, am=2, a=1, good=1, student=1, in=1}