Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

for (int i = 0; i < s.length(); ++i) 
    {
        if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') 
        {
            ++array[s.charAt(i) - 'A'];
        }
    }

I understand the For loop. the s.length() is 26, int[26] to be exact. so this loop will occur 26 times, 0-25. If the Char at i, 0-25 is between or are A-Z it will then proceed to ++array[s.charAt(i) - 'A']; From what i see it adds array once per loop, or adds the value of array once per loop, for the String at char i so the first one would be 0 second would be 2, because arrays start at 0. so adding an array at location of i -'A' is where i get confused.

like image 417
Renuz Avatar asked Nov 14 '11 08:11

Renuz


2 Answers

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.

like image 161
Mysticial Avatar answered Oct 01 '22 13:10

Mysticial


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

like image 36
Lukas Eder Avatar answered Oct 01 '22 13:10

Lukas Eder