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

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());
        }

    }

你可能感兴趣的:(java统计一段英文中单词及个数)