//统计所有的数据放入map,key为中文,value为出现的次数
HashMap<String, Integer> countMap = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
String substring = str.substring(i, i + 1);
if (countMap.get(substring) != null) {
countMap.put(substring, countMap.get(substring) + 1);//出现的次数+1
} else {
countMap.put(substring, 1);
}
}
//次数最多的map
HashMap<String, Integer> maxMap = new HashMap<>();
int maxNumber = 0;
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
Integer value = entry.getValue();
String regex = "[\\u4e00-\\u9fa5]";//字符串得是中文
boolean flag = Pattern.matches(regex, entry.getKey());
if (flag && value > maxNumber) {
maxNumber = value;
maxMap.clear();
maxMap.put(entry.getKey(), entry.getValue());
} else if (value == maxNumber) {//次数相同一起添加进去
maxMap.put(entry.getKey(), entry.getValue());
}
}
System.out.println(maxMap);//{务=34, 调=34}
获取String字符串里出现最多的中文
最新推荐文章于 2022-02-21 11:12:33 发布