1. 程式人生 > >Java 統計一個字串中每個單詞,或者字母出現的次數

Java 統計一個字串中每個單詞,或者字母出現的次數

package cn.itcast.demo24;


import java.util.HashMap;


/*
 * 用程式碼實現以下需求
(1)有如下字串"If you want to change your fate I think you 
must come to the dark horse to learn java"(用空格間隔)
(2)列印格式:
to=3
think=1
you=2
//........
(3)按照上面的列印格式將內容寫入到D:\\count.txt檔案中(要求用高效流)
 */
public class Demo22 {
public static void main(String[] args) {
String s = "If you want to change your fate I think you " +
"must come to the dark horse to learn java";
get(s);
}
public static void get(String s){
String[] str = s.split(" ");
HashMap<String, Integer> map = new HashMap<>();
for(String ss:str){
Integer num = map.get(ss);
if(num==null){
map.put(ss, 1);                  
}else {
map.put(ss, ++num);   ...................... //此處如果寫為  map.put(ss,num++),就會錯誤,
//否則就寫為  num++;
//          map.put(ss,num);
}
}
System.out.println(map);

}

  下面這樣寫也可以

/*for(String ss:str){
Integer num = map.get(ss);
if(num==null){
num = 1;                 
}else {
num++;
}
map.put(ss,num);
*/
}