How to keep count of different things in an array?

Viewed 108

I encountered a code which some parts I do not understand. It has something to do with keeping count of letters in a string. I have commented the part that I do not get. I would appreciate any help. Thank you!

I tried looking it up online but none seem to answer my question.

public class test2 {
    static int[] inventory;
    public static final int ALPHABET = 26;

    public static void main(String[] args) {
        inventory = new int [ALPHABET];
        String dog = "There goes the dog!";

        int size = count(dog);
        System.out.println(size);

    }

    private static int count(String data) {
        data = data.toLowerCase();
        int size = 0;
        for (int i = 0; i < data.length(); i++) {
            char ch = data.charAt(i);
            if (Character.isLetter(ch)) {
                size++;
                inventory[ch - 'a']++; // this I don't get
            }
        }
        return size;
    }
}
3 Answers

In this case, inventory is an array of size 26 which holds number of times each character appears in the string.

The statement you have put the comment on is trying to deduct the ASCII value of a which is 97 from the character in the string. For example, b's ASCII value is 98 and 'b' - 'a' is 1. So, inventory[1] is incremented i.e b appeared in your string once.

System.out.println(0 + 'c'); //ASCII value of 'c'; will print 99
System.out.println(0 + 'a'); //ASCII value of 'a'; will print 97
System.out.println('c' - 'a'); //Difference of ASCII values of characters; will print 99-97=2

In your case

inventory[ch - 'a']++;

ch will be some character.
ch - 'a' will be the distance of that character from 'a'. For example, as shown above, 'c' - 'a' = 2.
inventory[ch - 'a'] will point to the number at index ch - 'a' in the array.
inventory[ch - 'a']++ will increment that value by 1.

As per the above code, you're trying to count the number of each alphabets.
So, for each letter, let's assume you use a single bucket. Which is done by new int [ALPHABET];. So, you have 26 slots from 0 to 25.
Now, when you're counting the letters:
Each letter has a value assigned to it (ASCII value). ASCII value of lower case a a is 97. But, in your slot, you want to add a to slot 0. So, what do you do: you subtract 97 i.e. you subtract value of a for each letter.
So now, a is stored in slot 0, b in slot 1 and so on.

Related