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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With