用HashMap統計字串中各個“單詞”的數量
阿新 • • 發佈:2021-02-07
技術標籤:java
1.統計每個單詞出現的次數
2.有如下字串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格間隔)
3.列印格式:
to=3
think=1
you=2
//…
**=====================================================================**
public class Test {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//建立HashMap
Map<String, Integer> map = new HashMap<>();
String str = "If you want to change your fate I think you must come to the dark horse to learn java";
//以空格“ ”為分隔符,將單詞分割儲存到陣列strArr中
String[ ] strArr = str.split(" ");
//統計語句中的每個單詞出現的次數
for (String s : strArr) {
if (!map.containsKey(s)) {//map.containsKey():判斷map中是否存在所對應的key值
map.put(s, 1);
} else {
map.put(s, map.get(s) + 1);
}
}
//列印
System.out.println(map);
}
}
測試: