問題:統計一篇文章中單詞出現的次數
思路:
(1)將文章(一個字符串存儲)按空格進行拆分(split)后,存儲到一個字符串(單詞)數組中。
(2)定義一個Map,key是字符串類型,保存單詞;value是數字類型,保存該單詞出現的次數。
(3)遍歷(1)中得到的字符串數組,對於每一個單詞,考察Map的key中是否出現過該單詞,如果沒出現過,map中增加一個元素,key為該單詞,value為1(第一次出現);
如果,在map的key中發現了該單詞,則通過key找到對應的value(單詞出現的次數),將該value加1,再次保存回map。
(4)遍歷(3)中得到的map,輸出key(單詞)及對應的value(次數)。
demo代碼如下:
import java.util.HashMap;
import java.util.Iterator;
public class Has {
// 統計單詞出現的次數
public static String StatList(String str) {
StringBuffer sb = new StringBuffer();
HashMap<String ,Integer> has = new HashMap<String ,Integer> (); // 打開一個哈希表
String[] slist = str.split(" ");
for (int i = 0; i < slist.length; i++) {
if (!has.containsKey(slist[i])) { // 若尚無此單詞
has.put(slist[i], 1);
} else {//如果有,就在將次數加1
Integer nCounts = has.get(slist[i]);
has.put(slist[i],nCounts+1 );
}
}
//遍歷map
Iterator iterator = has.keySet().iterator();
while(iterator.hasNext()){
String word = (String) iterator.next();
sb.append("單詞:").append(word).append(" 次數").append(has.get(word)).append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
String s = new String("You are the mananger of an office supplies company. A colleague has received a letter compaining about an order for office furniture. She has left the letter for you to answer and has written some notes on it.");
System.out.println(StatList(s));
}
}
