java小算法—统计句子中每个单词出现的次数

 

代码

public class Test {

	public static void main(String[] args) {

		String words = "Look buddy, U got work hard and put yourself in your java, Once you learned the heart of the java, I can guarantee that you win.";

		//正则匹配
		String reg = "[a-zA-Z]+";
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(words);

		// 存放单词的集合
		HashMap map = new HashMap();
		int count = 0;// 单词总数
		while (m.find()) {
			count++;
			String w = m.group();
			if (null == map.get(w)) {// 此单词集合中没有 添加 数量为1
				map.put(w, 1);
			} else {// 已有 添加 数量+1
				int x = map.get(w);
				map.put(w, x + 1);
			}
		}
		// 单词总数
		System.out.println("单词总数:" + count);
		// 遍历集合keySet
		Set set = map.keySet();
		Iterator i1 = set.iterator();
		while (i1.hasNext()) {
			String key = i1.next();// key
			Integer value = map.get(key);// 值
			System.out.println("单词:" + key + "    出现次数:" + value);
			System.out.println("------------------------------------------");
		}

	}

}

 

 

结果

单词总数:26
单词:Look    出现次数:1
------------------------------------------
单词:buddy    出现次数:1
------------------------------------------
单词:work    出现次数:1
------------------------------------------
单词:heart    出现次数:1
------------------------------------------
单词:put    出现次数:1
------------------------------------------
单词:can    出现次数:1
------------------------------------------
单词:your    出现次数:1
------------------------------------------
单词:you    出现次数:2
------------------------------------------
单词:win    出现次数:1
------------------------------------------
单词:the    出现次数:2
------------------------------------------
单词:I    出现次数:1
------------------------------------------
单词:in    出现次数:1
------------------------------------------
单词:and    出现次数:1
------------------------------------------
单词:U    出现次数:1
------------------------------------------
单词:that    出现次数:1
------------------------------------------
单词:of    出现次数:1
------------------------------------------
单词:Once    出现次数:1
------------------------------------------
单词:learned    出现次数:1
------------------------------------------
单词:guarantee    出现次数:1
------------------------------------------
单词:java    出现次数:2
------------------------------------------
单词:yourself    出现次数:1
------------------------------------------
单词:got    出现次数:1
------------------------------------------
单词:hard    出现次数:1
------------------------------------------

你可能感兴趣的:(Java,常见算法)