level: beginner
Below snippet is part of code that counts letters in an array. How do you say this in english?
counts[letters[i] - 'a']++ ;
I understand the substraction mechanism but i’m a bit confused by the shorthand way to write the letter count incrementation.
full code:
class CountLettersInArray
{
public static void main(String[] args)
{
char[] letters = new char[100] ;
for (int i = 0 ; i < 100 ; i++ )
{
letters[i] = RandomCharacter.getRandomLowerCaseLetter() ;
}
int[] counts = new int[26] ;
for (int i = 0 ; i < 100 ; i++ )
{
counts[letters[i] - 'a']++ ;
}
for (int i = 0 ; i < 26 ; i++ )
{
System.out.print(counts[i] + " " ) ;
}
}
}
What is happening here, is that the letter a is a char, which has an integer value of 97.
So, by taking the character value, and subtracting the ascii value of ‘a’, it is making the array base zero. So, for each character it is incrementing the value in the array (remember all array values in an integer array start at zero).
So, it increments the relevant characters count in the array each time a character is found.