counting letters in an array (java)
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] + " " ) ;
}
}
}
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)
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.
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.
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'
.
精彩评论