Signup/Sign In

How to Count occurrence of a char in Java String

In this post, we are going to count the occurrence of a character in the string using Java code. A string is a sequence of characters that can contain duplicate characters as well.

So, if any string contains a character more than once and we want to check that character occurrence than we can use several methods of String class which helps to find the character frequency.

Here, we are using replace(), charAt(), and filter() method to find the character present in the string.

Time for an Example:

Let's create an example to find the character occurrence in the string. Here, we are using the replace() method that returns a string containing 'a' only and then difference of both string length is the result. The replace() method is not meant to find character occurrence but we can use it to build some logical code that produces the desired result.

public class Main {
	public static void main(String[] args){
		String str = "abracadabra-banana";
		System.out.println(str);
		// count occurrence 
		int count = str.length() - str.replace("a", "").length();
		System.out.println("occurrence of a: "+count);
	}
}


abracadabra-banana
occurrence of a: 8

Example: Java 8

Let's take another example to find character frequency. Here, we are using chars() method that returns a stream and then using filter() method to get all the 'a' present in the string. The count() method is used to get count of the filtered stream. Here, we are using Stream API concept of Java 8 version, See the example below.

public class Main {
	public static void main(String[] args){
		String str = "abracadabra-banana";
		System.out.println(str);
		// count occurrence 
		long count = str.chars().filter(ch -> ch == 'a').count();
		System.out.println("occurrence of a: "+count);
	}
}


abracadabra-banana
occurrence of a: 8

Example: Custom Code

This is a conventional solution of finding a character count in the string. Here, we are using a loop to traverse each character of the string and comparing character by using the charAt() method that returns a character present at the specified index and finally counting if a character matches the desired character.

public class Main {
	public static void main(String[] args){
		String str = "abracadabra-banana";
		System.out.println(str);
		// count occurrence 
		int count = 0;
	    for (int i=0; i < str.length(); i++)
	    {
	        if (str.charAt(i) == 'a')
	        {
	             count++;
	        }
	    }
		System.out.println("occurrence of a: "+count);
	}
}


abracadabra-banana
occurrence of a: 8



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.