What does count[s1.charAt(i) - 'a']++ do within the following for loop? I saw a similar question answered here but I’m still confused. I’ve never seen this syntax before and have not been able to find a lot of info about it.
String s1 = "abcd";
int[] count = new int[26];
for (int i = 0; i < len1; i++) {
count[s1.charAt(i) - 'a']++;
}
>Solution :
Let’s examine the expression count[s1.charAt(i) - 'a']++; from the inside out.
s1.charAt(i) is the character in the ith place of the s1 string. Since letters are sequential, subtracting a from this character will convert it to an index in the count array (a is turned to 0, b is turned to 1, etc). Then, the subscript operator [] is used to reference that index in the array. And finally, ++ is used to increment the value of the array in that index.
If we put it all together – count is an array of counters for each character in the string. The loop goes over the characters in the string, and for each character increments the appropriate counter, so when its done the array will hold the counts of each character in it.