An evenA possibly faster, and at least more compact version than using a HashMap
is to use a good old integer array. A char
can actually be typecasted to an int
, which gives it's ASCII code value.
String str = "Hello World";
int[] counts = new int[256];int[(int) Character.MAX_VALUE];
// If you are certain you will only have ASCII characters, I would use `new int[256]` instead
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
counts[(int) charAt]++;
}
System.out.println(Arrays.toString(counts));
As the above output is a bit big, by looping through the integer array you can output just the characters which actually occur:
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
System.out.println("Number of " + (char) i + ": " + counts[i]);
}