Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Find the Frequency of Character in a String


In this article, we will understand how to to find the frequency of character in a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

Input string: Java Programming is fun
Input character: a

The desired output would be

The frequency of a is 3

Algorithm

Step 1 - START
Step 2 - Declare a string namely input_string, a char namely input_character, an int value na,ely counter.
Step 3 - Define the values.
Step 4 - Iterate over the string using a for-loop, compare each letter of the string with the character provided. If the character matches, increment the counter value.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Demo {
   public static void main(String[] args) {
      String input_string = "Java Programming is fun";
      System.out.println("The string is defined as: " +input_string);
      char input_character = 'a';
      System.out.println("The character is defined as: " +input_character);
      int counter = 0;
      for(int i = 0; i < input_string.length(); i++) {
         if(input_character == input_string.charAt(i)) {
            ++counter;
         }
      }
      System.out.println("The frequency of " + input_character + " is " + counter );
   }
}

Output

The string is defined as: Java Programming is fun
The character is defined as: a
The frequency of a is 3

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

public class Demo {
   public static int get_count(String input_string,char input_character) {
      int counter = 0;
      for (int i = 0; i < input_string.length(); i++) {
         if (input_character == input_string.charAt(i)) {
            ++counter;
         }
      }
      return counter;
   }
   public static void main(String[] args) {
      String input_string = "Java Programming is fun";
      System.out.println("The string is defined as: " +input_string);
      char input_character = 'a';
      System.out.println("The character is defined as: " +input_character);
      int counter = get_count(input_string, input_character);
      System.out.println("The frequency of " + input_character + " is " + counter );
   }
}

Output

The string is defined as: Java Programming is fun
The character is defined as: a
The frequency of a is 3