public class MyTest2 {
public static void main(String[] args) {
/*
"aababcabcdabcde", 获取字符串中每一个字母出现的次数要求结果:a(5) b(4) c(3) d(2) e(1)*/
Scanner sc = new Scanner(System.in);
System.out.println("请随便输入一段字符串");
String s = sc.nextLine();
//通过观察,发现数据是这种键值映射关系的数据,那么就可以使用双列集合来存储
HashMap<Character, Integer> map = new HashMap<>();
//难点在于统计每个键的个数
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
//统计个数,存到集合中
if (!map.containsKey(ch)) {
map.put(ch, 1);
} else {
Integer v = map.get(ch);
v++;
//键相同,值覆盖
map.put(ch, v);
}
}
Set<Character> keySet = map.keySet();
StringBuilder sb = new StringBuilder();
for (Character key : keySet) {
Integer value = map.get(key);
sb.append(key).append("(").append(value).append(") ");
}
System.out.println(sb.toString());
}
}
方法II:
class Test {
public static void main(String[] args) {
String str="sadr ew133365ewds d";
char[] chars = str.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < chars.length; i++) {
if (!map.containsKey(chars[i])){
map.put(chars[i],1);//如果集合不存在这个键,则添加此键,并将值置为1
}else {
map.put(chars[i],map.get(chars[i])+1);//如果存在此键,将此键对应的值加1
}
}
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
Integer value = entry.getValue();
Character key = entry.getKey();
System.out.println(key+" "+value);
}
}
}