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

前端 未结 5 944
遥遥无期
遥遥无期 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:32

    The statement ++array[s.charAt(i) - 'A']; is incrementing the value in the array indexed by s.charAt(i) - 'A'.

    What this loop does is that it counts up the number of occurrences of each letter in s.

    The reason for - 'A', is that it "shifts" the ascii/unicode value so that A - Z have values 0 - 25. And are thus more suitable as an array index.

    0 讨论(0)
  • 2020-12-30 16:32

    count chars

    (count chars is not a historical figure)

    0 讨论(0)
  • 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<count.length;i++) {
            System.out.println(counter++ + " " + count[i]);
        }
    

    }

    0 讨论(0)
  • 2020-12-30 16:46

    array seems to be a "counter per capital letter". By subtracting character 'A' from an arbitrary character in a string, you get the letter's index in the array:

    'A' - 'A' == 0
    'B' - 'A' == 1
    'C' - 'A' == 2
    

    To understand this, you should understand, that Java treats char the same as (unsigned) short. Hence, you can make calculations with char

    0 讨论(0)
  • 2020-12-30 16:46
    ++array[s.charAt(i) - 'A'];
    

    count frequency of each character in given string s and store the frequency of each character at a particular index in the array.

    0 讨论(0)
提交回复
热议问题