Reputation:
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] + " " ) ;
}
}
}
Upvotes: 1
Views: 3140
Reputation: 8290
Try to look at that like this:
int letterPositionInCountArray = letters[i] - 'a'; // i.e for a - 0, b - 1 etc
counts[letterPositionInCountArray]++; // increment that position
Btw, it is better practice to use [digit][1] method.
[1]: http://download.oracle.com/javase/6/docs/api/java/lang/Character.html#digit(char, int)
Upvotes: 1
Reputation: 200170
letters[i]
is some ascii code that represent a letter, say x. Then - 'a'
works as following: if letters[i] == 'a'
then it will mean 0 (because x-x= 0). If letters[i] == 'b'
(x+1) then it will mean 1 (because x+1-x=1). Thus, you are incrementing the value in the position letters[i] - 'a'
.
Upvotes: 0
Reputation: 54944
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.
Upvotes: 0
Reputation: 25511
The code is incrementing the element of the counts
array.
See Postfix Increment Operator ++ in the Java Language Spec for more information about this operator.
Upvotes: 0