编写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));
}
}
}