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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With