How to keep count of different things in an array?

Niko :

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;
    }
}
Kartik :
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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76520&siteId=1