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.
The statement
++array[s.charAt(i) - 'A'];is incrementing the value in the array indexed bys.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 thatA - Zhave values 0 – 25. And are thus more suitable as an array index.