Java program to count occurrences of a character in String

Java program to count occurrences of a character in String

Write a Java program to count occurrences of a character in String is a common programming interview question for freshers. The question is used to test candidate’s ability to write code. There is no in-built API available in the String class to directly find the count. Hence we need to implement our own logic to find the number of occurrences of a character in a String. Here we will see four approaches of solving the problem.

Approach#1: Using enhanced for loop

Approach#2: Using ordinary for loop

In the above program instead of iterating the string from start to end, we can also setup the for loop to iterate from first occurrence of the given character to last occurrence as below,
Note that based on the input, the above for loop can take higher execution time because of the overhead in finding the first and last index.

Approach#3: Using Recursion

Approach#4: Using length()

You can also use third party libraries like Apache Commons to easily find the count of characters. Use the StringUtils.countMatches() method for the same.

The program might look simple but it is important to remember the logic so that it will become easy to write it during an interview. These solutions can also be extended to find occurrences of a substring.

Hope you find the post useful.

Also read my posts on Frequently asked Java interview questions with answers.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
  1. I do prefer the option to use commons.lang.StringUtils library and the countMatches() method. That library has some great tools for dealing with String.

    • ‘.’ is a pattern token that defines “Any character”. Check the Pattern class in Java for more information.
      The next() method returns the string matching the pattern. In this case it returns any character.
      I hope it helps.

Add Comment

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