给定一个字符串,怎么输出相同字符出现多少次
2 回答
已采纳
尧叔
TA贡献77条经验 获得超201个赞
public static void main(String[] args) { String s = "snakeasdfasdfagdsafas"; char[] chars = s.toCharArray(); Map<Character, Integer> map = new HashMap<Character, Integer>(); for (char aChar : chars) { if (!map.containsKey(aChar)) { map.put(aChar, 1); }else { Integer i = map.get(aChar); i++; map.put(aChar, i); } } for (Map.Entry<Character, Integer> characterIntegerEntry : map.entrySet()) { System.out.println(characterIntegerEntry.getKey() + "出现" + characterIntegerEntry.getValue() + "次"); } }
谢谢采纳!
添加回答
举报
0/150
提交
取消