Find Frequency of a Character in a Given String in Java



For a given a string, write a Java program to find the frequency of a particular character. In Java, String is a datatype that contains one or more characters and is enclosed in double quotes(" ").


Finding Frequency of a Character in a String

To find the Frequency of a character in a given String, follow the below ways ?

  • Using for Loop
  • Using Stream API

Using for loop

In this approach, use the for loop to compare each character in the given string with the character whose frequency you want to find. Increment the count each time a match occurs.

Example

In this example, we use the nested for loop to find the frequency of a character in a given string.

public class FrequencyOfACharacter {
   public static void main(String args[]){
      String str = "Hi welcome to tutorialspoint";
      System.out.println("Given string value:: " + str);
      char character = 't';
      System.out.println("Finding frequency of character:: " + character);
      int count = 0;
      for (int i=0; i<str.length(); i++){
         if(character == str.charAt(i)){
            count++;
         }
      }
      System.out.println("Frequency of the given character:: "+count);
   }
}

When you run the code, it will show the below result ?

Given string value:: Hi welcome to tutorialspoint
Finding frequency of character:: t
Frequency of the given character:: 4

Using Stream API

This is another approach to find frequency of a character in a given string. Here, we use the Java streams which is used to process a collection of objects. In this approach, the filter() method will filter out those characters that matches the given character.

Example

The following example explains how to find the frequency of a character in a given String with the help of stream API.

import java.util.stream.IntStream;
public class FrequencyOfACharacter {
   public static void main(String[] args) {
      String str = "Hi welcome to tutorialspoint";
      System.out.println("Given string value:: " + str);
      char character = 'i';
      System.out.println("Finding frequency of character:: " + character);
      long count = IntStream.range(0, str.length())
                  .mapToObj(i -> str.charAt(i))
                  .filter(ch -> ch == character)
                  .count();

      System.out.println("The frequency of '" + character + "' is:: " + count);
   }
}

On running, this code will produce following output ?

Given string value:: Hi welcome to tutorialspoint
Finding frequency of character:: i
The frequency of 'i' is:: 3
Updated on: 2024-07-31T19:54:06+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements