Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting every single letter in an array with ASCII table (Unicode code)

Tags:

java

arrays

I am new at Java and I could not understand this structure:

public static int[] upperCounter(String str) {
    final int NUMCHARS = 26;
    int[] upperCounts = new int[NUMCHARS];
    char c;

    for (int i = 0; i < str.length(); i++) {
        c = str.charAt(i);
        if (c >= 'A' && c <= 'Z')
            upperCounts[c-'A']++;
    }

    return upperCounts;
}

This method works, but what does list[c-'A']++; mean?

like image 430
funky-nd Avatar asked Dec 12 '22 02:12

funky-nd


1 Answers

c - 'A' is taking a character in the range ['A' .. 'Z'], and subtracting 'A' to create a numerical value in the range [0 .. 25] so it can be used as an array index.

upperCounts[c - 'A']++ increments the occurrence count for the character c using its corresponding index c - 'A'.

Effectively, the loop is generating an array of character type counts.

like image 82
user123 Avatar answered Dec 28 '22 07:12

user123