计算一个字符串中每个字符出现的次数

话不多说,上代码,

//通过treeMap
    public static void getCount(String str){
        if(str.length() == 0 && str == null){
            return;
        }
        Map<Character,Integer> map = new TreeMap<Character,Integer>();

        for(int i = 0;i < str.length();i++){
            char c = str.charAt(i);
            int count = 1;
            if(map.containsKey(c)){
                count = map.get(c) + 1;

            }
                map.put(c,count);
        }
        System.out.println(map);
    }



第二种:
public static void getCount1(String str){
        //先判断该字符串是否为空或者没有
        if(str == null && str.length() == 0){
            return;
        }

        Map<Character,Integer> map = new TreeMap<>();

        for(int i  = 0;i < str.length();i++){
            char c = str.charAt(i);
            //利用键的不重复性
            Integer count = map.get(c);
            //如果count为null,表示该字符是第一次出现,默认给它1
            if(count == null){
                count = 1;
            }else{
                //表示出现过了,在map中
                count++;
            }
            map.put(c,count);

        }
        System.out.println(map);
    }




第三种:


public static void getCount3(String str){

        int[] arr = new int[123];
        //先遍历字符串
        for(int i = 0;i < str.length();i++){
            //那就可以将每个遍历到的字符作为数组的下标,出现的个数作为它对应索引的值
            int index = str.charAt(i);
            arr[index]++;

        }

        for(int i = 0;i < arr.length;i++){
            if(arr[i] != 0){
                System.out.println((char)i +" "+arr[i]);

            }

        }

    }
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值