[wp-night-mode-button]

Count occurrences of Character in String

Count the Number of Occurrences of a Character in a String in Java

In this article, we will look at a problem: Given an Input String and a Character, we have to Count Occurrences Of character in String.

[toc]

For Example, If the Given String is : "Java2Blog" and we have to count the occurrences of Character ‘a’ in the String.

Therefore, Count of 'a' is : 2 , in the String “Java2Blog” . We will discuss different approaches to do this :

Note: The search of the Character will be Case-Sensitive for any String.

1. Using String Library Methods

This is the most conventional and easiest method to follow in order to find occurrences of character in a string . For this, we use the charAt() method present in the String Class of java.lang package. The signature of method is :

public char charAt(index) – index of the character to be found.

  • Iterate throughout the length of the input String
  • Check whether each character matches the character to search
    • If yes, increment the count
    • else do nothing
Let us look at the implementation:

public class CountOccurences
{
  public static void main(String args[]) 
  {
      
  String input = "aaaabbccAAdd";
  char search = 'a';             // Character to search is 'a'.
  
  int count=0;
  for(int i=0; i<input.length(); i++)
  {
      if(input.charAt(i) == search)
      count++;
  }
  
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

2. Using Recursion

This is a rather interesting and tricky solution. Here, we call our function for the start index 0 of the String. If character matches to searched character, we add 1 to our result variable and recur for index+1, until we reach the end point of the string.

Let us look at the code:

public class CountOccurences
{

  static int findOccurrences(String str, char search, int index)
  {
      if(index >= str.length())
      return 0;
      
      int count=0;
      
      if(str.charAt(index) == search)
      count++;
      
      return count + findOccurrences(str,search,index+1);
  }
   
  public static void main(String args[]) 
  {
      
  String input = "aaaabbccAAdd";
  char search = 'a';             // Character to search is 'a'.
  
  int result = findOccurrences(input,search,0); //start index 0 for       start of string.
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

3. Using Hashing Concept

Using Arrays

In this approach, we use a primitive integer type array of size 26. Then for each character in the string we encounter we increment it’s hash value in the array. For each character, char its index in array will be : Arr[ char – 97].

Note: This is a Case Sensitive Approach. If we use Uppercase Characters the index value will be: Arr[ char – 65]. The space we use is constant does not depend on size of input String.

Let us look at the implementation.

public class CountOccurences
{
   
  public static void main(String args[]) 
  {
 
  String input = "aaaabbcccddd";
  char search = 'a';             // Character to search is 'a'.
  
  int hash_arr[] = new int[26];
  
  for(int i=0;i<input.length();i++)
  {
      hash_arr[input.charAt(i) - 97]++;
  }
  
  int result = hash_arr[search-97]; // we get count value of character from the array.
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Using Collections (Map)

Here we will do the same thing as above for each character in the input string we will put it in our Map with value 1, if it is seen for the first time. If the character repeats or the character is already present in our Map, we update the value of the character in the map by adding 1 to it. We can use any type of Map; HashMap, TreeMap, https://java2blog.com/linkedhashmap-in-java-with-example/. In this example we used a simple HashMap.

Note: This approach works for both Uppercase and Lowercase Characters. Hence, Case In-Sensitive.

import java.util.*;
public class CountOccurences
{
   
  public static void main(String args[]) 
  {
      
  String input = "aaaabbAAAAcccddd";
  char search = 'a';             // Character to search is 'a'.
  
  Map<Character,Integer> hash = new HashMap<Character,Integer>();
  
  for(int i=0;i<input.length();i++)
  {
      if(hash.containsKey(input.charAt(i)))
      hash.put(input.charAt(i), hash.get(input.charAt(i))+1);
      
      else
      hash.put(input.charAt(i), 1);
  }
  
  int result = hash.get(search);
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

4. Using Java 8 Features

If we use Java 8 or above JDK Version, we can use the feature of lambdas and Stream to implement this. We will use the `IntStream` class methods, `chars()` method and `codePoints()` method which returns the integer codepoints (Unicode value) of the character stream. We will then filter them using Lambda expression with the search character and count their occurrences using count method. We will look at each of their implementation.

import java.util.*;
public class CountOccurences
{
  public static void main(String args[]) 
  {
      
  String input = "aaabbAAAAAcccd";
  char search = 'A';             // Character to search is 'a'.
  
  //Example 1
  long count = input.chars().filter(ch -> ch == search).count();
  // chars() method return integer representation of codepoint values of the character stream
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  
  
  //Example 2
  count = input.codePoints().filter(ch -> ch == search).count();
  // codePoints() just return the actual codepoint or Unicode values of the stream.
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  
  }
}

Output:

The Character 'A' appears 5 times.
The Character 'A' appears 5 times.

So that’s it for how to count Occurrences Of Character in String, you can try out with other examples and execute the code for better understanding.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.