Character count in string Java
Problem
Write a Java program to find character counts in a string consisting from capital letters (A to Z) only. The program must not use nested loops. Hash tables that are built in to the language must not be used as well. For example if the input string is “CACBACDDDD” the output of the program should be something like:
1 2 3 4 |
A:2 B:1 C:3 D:4 |
How to get character counts
Loop through the characters of the string character by character. Update “a counter” of the current character. The trick here is to automatically update the correct counter based on the current character occurrence. For example when A is read the program has to update the counter for A not for B. We can use an array of counters of size 28. The first position in the array holds the counter for A and the last position holds the count for Z. In order to find the correct counter position in the counters array given a character we subtract the ASCII code of A from the ASCII code of that character then use the result to index the counters array. Once we do that we just increment the counter.
Java program
Check out the following method in Java. Notice that it prints out all counts for all possible characters. If you want to get a specific repeating character, you may add one if statement to print the count for a certain character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
public class Test { public static void main(String[] args) { //Sample string String str = "CACBACDDDD"; //Array of integer counters. We need 28 counters //to cover 28 characters from A-Z int[] counters = new int[28]; //Get the ASCII code of A int ia = (int)'A'; //Loop through the characters of the string for (char c : str.toCharArray()) { //Get the ASCII code of the current character int ic = (int)c; //Increment the appropriate counter given //the current character. Notice that the //position of the counter is calculated //relative to the first counter using ASCII codes. //This is nothing but a simple hashing technique. counters[ic - ia]++; } //Print the characters and their counts for (int i = 0; i < 28; i++) //Only if count is not zero if (counters[i] > 0) { //Notice how we get the character from its ASCII code //and notice how the calculation is always relative //to the first character A System.out.print((char)(ia + i)); System.out.println(" : " + counters[i]); } } } |