java统计字符串中每个字符出现的次数

例如String str = “abcaaaefdabbhg”;
统计该字符串中每个字符出现的次数,输出:
a====5
b====3
c====1
d====1
e====1
f====1
g====1
h====1

方法一:
采用HashMap

public static void count(String str){
        //将字符串转化为字符数组
        char[] chars = str.toCharArray();
        //创建一个HashMap名为hm
        HashMap<Character,Integer> hm = new HashMap();

        //定义一个字符串c,循环遍历遍历chars数组
        for(char c : chars){
            //containsKey(c),当c不存在于hm中
            if(!hm.containsKey(c)){
            hm.put(c,1);
          }else{ 
          //否则获得c的值并且加1
            hm.put(c, hm.get(c)+1);
            }

        //或者上面的if和else替换成下面这一行
        /*  hm.put(c,hm.containsKey(c) ? hm.get(c)+1:1);*/
        }


        for(Character key: hm.keySet()){
            //hm.keySet()代表所有键的集合,进行格式化输出
            System.out.println(key + "====" + hm.get(key));
        }
    }

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        String str = "abcaaaefdabbhg";
        count(str);
    }

}

方法二:

 public static void count(String str){
    //创建26个空间大小的数组,存放26个字母
        int[] nums = new int[26];
        for(char i: str.toCharArray()){
        //自动将char i转化成ascall码
            if(i>=97 && i<= 122){
            //利用数组的索引进行存储
                nums[i-97]++;
            }
        }
        for(int i = 0; i< nums.length; i++){
            if(nums[i] != 0){
                //i加上97并且再转化为char类型就可以显示相应的字符
                char j = (char)(i+97);
                System.out.println( j + "====" + nums[i]);
            }
        }
    }

和方法1一样在main函数中调用就可以啦!

版权声明:http://blog.csdn.net/csdn_zsdf/article/details/76038276

猜你喜欢

转载自blog.csdn.net/qq_17011423/article/details/79560684
今日推荐