Write a program to count number of occurrence of a character in String is one of common programming interview question not just in Java but also in other programming language like C or C++. As String in a very popular topic on programming interviews and there are lot of good programming exercise on String like "count number of vowels or consonants in String", "count number of characters in String" , How to reverse String in Java using recursion or without using StringBuffer etc, it becomes extremely important to have solid knowledge of String in Java or any other programming language. In Interview, most of the time Interviewer will ask you to write program without using any API method, as Java is very rich and it always some kind of nice method to do the job, But it also important to know rich Java and open source libraries for writing production quality code. Anyway in this question we will see both API based and non API based(except few) way of to count number of occurrence of a character in String on Java.
Java program to count occurrence of a character in String
In this Java program we will see couple of ways to count, how many times a particular character is present in String. First we we will see Spring framework’s StringUtils class and its static method countOccurrenceOf(String, character) which takes a String and character and returns occurrence of character into that String. After that we will see Apache commons StringUtils class for counting occurrence of a character in String. Apache commons StringUtils provide countMatches() method which can be used to count occurrence of one character or substring. Finally we will see most simple way of counting character using standard for loop and Java 5 advanced for loop. This solution can be extended not just for finding occurrence of character but also finding occurrence of substring.
Well beauty of this questions is that Interviewer can twist it on many ways, they can ask you to write a recursive function to count occurrence of a particular character or they can even ask to count how many times each characters has appear. So if a String contains multiple characters and you need to store count of each character, consider using HashMap for storing character as key and number of occurrence as value. Though there are other ways of doing it as well but I like the HashMap way of counting character for simplicity.
Other programming exercise for Java programmer