I was going through a piece of code which i was not able to understand. Thought of checking this with our community.
In the below code, i am not able to understand what the line count[ch-'a']++ does. or how can we write the same in java 7. What the explanation says is that we have a String s and an int array count. We iterate through the string s and count the no of occurrences of the characters in s and put the frequencies of count into the array. please help!!
String s = "test";
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
count[ch-'a']++;
}
the code is trying to count the number of occurrence of each character.
and it allocates it such that
a occupies position 0
b occupies position 1
etc etc
to get position 0, you need to call 'a' - 'a'
to get position 1, you need to call 'b' - 'a'
so what is happening in "count[ch-'a']++;" is eqivalent to
int position = ch -'a'; // get position
count[position] = count [position] + 1; // increment the count in that particular position
You are iterating over an array of ints count and incrementing the integer value at index ch-'a', which results in an integer value, e.g count['a'-'a'] == count[0] to flag that the character exists in the string.
you subtract in ch - 'a' because the integer value of alphabetic characters does not start at 0.
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