Java使用数组、二维数组、HashMap统计字符串中每个字符出现的次数


要求:给定一个字符串,统计每个字符出现次数

第一种思路,利用HashMap的特性,key不能重复,用来储存出现字符,value可以刷新,用来储存字符出现字数

 1 public static void main(String[] args) {
 2         //字符串中各字母个数
 3         String s = "safhuiwganlndvlznilenflawenvlav";
 4         Map<Character, Integer> map = new HashMap<>();
 5         char[] c = s.toCharArray();//将字符串转化为字符数组
 6         for (int i = 0; i < c.length; i++) {
 7             int count = 1;//初始计数为1
 8             if (map.containsKey(c[i])) {//判断map中是否含该字符
 9                 count += map.get(c[i]);//原计数+1
10                 map.put(c[i], count);
11             } else {//不含该字符直接存入,计数为1
12                 map.put(c[i], count);
13             }
14         }
15         System.out.println("字符串中各字符个数:");
16         System.out.println(map);
17     }
字符串中各字符个数:
{a=4, d=1, e=2, f=2, g=1, h=1, i=2, l=5, n=5, s=1, u=1, v=3, w=2, z=1}

 

第二种思路,使用s.length*2的int二维数组,每一行储存字符的码值和出现次数,注意字符0的存储

public static void main(String[] args) {
        String s = "safhuiwganlndvlznilenflawenvlav0765054162011";
        char[] c = s.toCharArray();
        int[][] a = new int[s.length()][2];
        for (int i = 0; i < c.length; i++) {
            for (int j = 0; j < a.length; j++) {
                int count = 1;
                if (c[i] == a[j][0] && a[j][1] > 0) {//如果数组已经包含该字符
                    a[j][1] += count;//计数+1
                    break;
                } else if (a[j][0] == 0 && a[j][1] == 0) {//如果该字符没出现过,遍历到空位置置入字符
                    a[j][0] = c[i];
                    a[j][1] = count;
                    break;
                }
            }
        }
        System.out.println("字符串中各字符个数:");
        for (int i = 0; i < a.length; i++) {
            if (a[i][1] > 0) {
                System.out.println((char) a[i][0] + ":" + a[i][1]);
            }
        }
    }
字符串中各字母个数:
s:1
a:4
f:2
h:1
u:1
i:2
w:2
g:1
n:5
l:5
d:1
v:3
z:1
e:2
0:3
7:1
6:2
5:2
4:1
1:3
2:1

 

第三种思路,通过字符特性,每个字符都有一个unicode码值,建立65535长度的一维数组,数组下标既为字符储存位置,数组内容存储出现次数

@Test
    public void work() {
        String string = "alksdflaksjdflkasjfd2398407239874238974238974我是汉字我是汉字我是汉字我是汉字我是汉字我是汉字我是汉字我是汉字我是汉字我是汉字我是汉字328╮(╯_╰)╭23回去时间3lkjalksjdflkajsdf";
        int[] arr = new int[65535];// 大数组, 即使所有字符出现也不怕冲突
        for (int i = 0; i < string.length(); i++) {
            char ch = string.charAt(i);
            arr[ch]++; // 用字符码值直接作为下标, 修改它对应的次数
        }
        System.out.println("字符串中各字符个数:");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 0) {
                System.out.println((char)i + " : " + arr[i]);
            }
        }
    }
字符串中各字符个数:
( : 1
) : 1
0 : 1
2 : 6
3 : 7
4 : 4
7 : 4
8 : 5
9 : 4
_ : 1
a : 5
d : 5
f : 5
j : 5
k : 6
l : 6
s : 5
╭ : 1
╮ : 1
╯ : 1
╰ : 1
去 : 1
回 : 1
字 : 11
我 : 11
时 : 1
是 : 11
汉 : 11
间 : 1

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM