统计字符串中每个字符的个数
程序员文章站
2022-06-28 18:48:43
public static void main(String[] args) { String str = "abbcccfggfydddd"; m7(str);}public static void m7(String str) { Map map = new HashMap<>(); for (int i = 0; i < str.length(); i++) { Character...
思路:将字符串转换为char数组,利用HashMap的特性来计算重复字符的个数
public static void main(String[] args) {
String str = "abbcccfggfydddd";
countChar(str);
}
public static void countChar(String str) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
//获取字符串中的单个字符
Character c = str.charAt(i);
//判断该字符是否已存在
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
//存在,则数量加1
map.put(c, map.get(c) + 1);
}
}
map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
//将Map存入List,然后根据数量排序
List<Map.Entry<Character, Integer>> list = new ArrayList<>();
list.addAll(map.entrySet());
Collections.sort(list,Comparator.comparing(o -> o.getValue())); //默认升序
//Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); //重写比较器,降序排列
list.forEach(System.out::println);
}
//输出结果:
a:1
b:2
c:3
d:4
f:2
g:2
y:1
a=1
y=1
b=2
f=2
g=2
c=3
d=4
本文地址:https://blog.csdn.net/MDW12345/article/details/107411670