1

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] + " " ) ;
        }

    }
}
1
  • 1
    Are you confused on what its doing? Or are you asking how would you phonetically pronounce that expression, i.e counts array of subscript of letters array at index i minus literal 'a' incremented? Commented Oct 31, 2010 at 16:50

4 Answers 4

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

thanks for that! got it now: "it is incrementing the value in the array" so if 'a' is encountered the first time, the value of count[0] is incremented by 1 resulting in count[0] = 1
0

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.

Comments

0

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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.