What exactly does ++array[s.charAt(i) - 'A'] do?

前端 未结 5 943
遥遥无期
遥遥无期 2020-12-30 16:26
for (int i = 0; i < s.length(); ++i) 
    {
        if (s.charAt(i) >= \'A\' && s.charAt(i) <= \'Z\') 
        {
            ++array[s.charAt(i) - \         


        
5条回答
  •  囚心锁ツ
    2020-12-30 16:38

    What is count[str.charAt(i)]++ actually storing? [duplicate] for those guys who have the same related question here is the answer

    First

    static final int chars=256; static char count[]=new char[chars];

    when we change this code into image it become like this

    0 1 2 3 4 5 6 7 8 9 .. .. .. .. .. .. .. 97 .. 255

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    Second

    count[str.charAt(i)]++;

    Let say you have str = “abc” Then str.charAt(0) will be “a” Then count[‘a’] means count[97] why? Because java automatically converted ‘a’ into ASCII code number 97; Then count[97] value is 0 when you increment it like this count[97]++ then it will become 1

    0 1 2 3 4 5 6 7 8 9 .. .. .. .. .. .. .. 97 .. 255

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

    if you increment it again like count[97]++ then it will become 2.

    0 1 2 3 4 5 6 7 8 9 .. .. .. .. .. .. .. 97 .. 255

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0

    That is the whole the secret behind. I do not describe the rest because I think your question is answered. If you want to test what I said is correct check it using this simple code

    public static void main(String[] argv) {

     int[] count = new int[255]; 
        count['a']++;
        System.out.println(count['a']);
        int counter=0;
        for(int i=0;i

    }

提交回复
热议问题