编写Java程序分析字符串中每个单词的个数

编写Java程序分析字符串中每个单词的个数

public class Test {
	public static void main(String[] args) {
		 String str = "I am Geng.X.y,she is my girlfriend.Lowood?what is that that?";
		//使用正则表达式分割过滤单词
//		String[] split = str.split("|\\.|,|\\?");
		String[] split = str.split(" |\\.|,|\\?");
		
		TreeMap<String, Integer> map = new TreeMap<>();
		for (int i = 0; i < split.length; i++) {
//			获取到每一个单词
			Integer integer = map.get(split[i]);
//			如果这个单词在map中没有,赋值1
			if(null==integer){
				map.put(split[i], 1);
			}else{
//				如果有,在原来的个数上加上一
				map.put(split[i], ++integer);
			}
		}
//		遍历,根据key获取所对应的value
		Set<String> keySet = map.keySet();
		for (String string : keySet) {
			System.out.println(string+":"+map.get(string));
		}
	}
}


猜你喜欢

转载自blog.csdn.net/yz972641975/article/details/52619650