您的位置:首页 > 编程语言 > Java开发

java统计一段英文中单词及个数

2017-10-19 23:01 267 查看
public static void countWords(String str){

Map<String, Integer> map=new HashMap<String, Integer>();
Pattern p=Pattern.compile("\\b[a-zA-Z-]+\\b");//正则表达式
Matcher m=p.matcher(str);
while(m.find()){
String mstr=m.group();
if(map.containsKey(mstr)){
map.put(mstr,map.get(mstr)+1);
}else{
map.put(mstr, 1);
}
}
Set<Entry<String, Integer>> entrySet = map.entrySet();
Iterator<Entry<String,Integer>> it=entrySet.iterator();
while(it.hasNext()){
Entry<String, Integer> next = it.next();
System.out.println(next.getKey()+" 个数:"+next.getValue());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  正则表达式re