如何统计某字符串中某个字符的数量

如题所述

private static void ma2() {
Scanner scanner = new Scanner(System.in);
System.out.println("输入内容..");
String s = scanner.nextLine();
Map<Character, Integer> map = new HashMap<>();
for(int i = 0;i<s.length();i++){
if(!map.containsKey(s.charAt(i))){
map.put(s.charAt(i), 1);
}else{
map.put(s.charAt(i), map.get(s.charAt(i))+1);
}
}
Set<Entry<Character, Integer>> entry = map.entrySet();
for(Entry<Character, Integer> e : entry){
System.out.println("值:"+e.getKey()+"--次数:"+e.getValue());
}
}
温馨提示:答案为网友推荐,仅供参考
相似回答