为了账号安全,请及时绑定邮箱和手机立即绑定

怎么输出字符串中相同字符出现的次数

怎么输出字符串中相同字符出现的次数

HelloWord3 2017-04-01 22:54:53
给定一个字符串,怎么输出相同字符出现多少次
查看完整描述

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() + "次");
    }

}

谢谢采纳!

查看完整回答
3 反对 回复 2017-04-01
  • 2 回答
  • 2 关注
  • 1391 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信