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:

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.

Add a Comment

Your email address will not be published. Required fields are marked *