问题:统计一篇文章中单词出现的次数
思路:
(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));
}
}