import java.util.HashMap;
import java.util.Iterator;
/**
* @author Administrator
* 2011-10-20 9:25
*/
//哈希表计出现次数
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("\\b");
for (int i = 0; i < slist.length; i++) {
if (!has.containsKey(slist[i])) { // 若尚无此单词
has.put(slist[i], 1);
} else {//如果有,就在将次数加1
has.put(slist[i],has.get(slist[i])+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));
}
}
java统计一篇文章中单词出现的次数
原创
©著作权归作者所有:来自51CTO博客作者踏行天下的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
测试一篇文章
我是标题第一章写一段代码
Linux 一篇文章 -
java按单词出现次数统计单词
import java.util.*;public class WordOccurrence implements Comparable { private String word; private int coun
java j2se Collection TreeMap i++ -
一篇文章搞懂Java反射
一.概念Reflection(反射)是被称为动态语言的关键,反射机制允许程序在执行期间借助于Refle
java 反射 class 构造器 父类