for (int i = 0; i < s.length(); ++i)
{
if (s.charAt(i) >= \'A\' && s.charAt(i) <= \'Z\')
{
++array[s.charAt(i) - \
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.
count chars
(count chars is not a historical figure)
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]);
}
}
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
++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.