Java program to find the Frequency of a character in a given String


To find the Frequency of a character in a given String

  •  Read a string from the user.
  •  Read the character.
  •  Create an integer variable initialize it with 0.
  •  Compare each character in the given string with the entered character increment the above created integer variable each time a match occurs.

Example

import java.util.Scanner;
public class FrequencyOfACharacter {
   public static void main(String args[]){
      System.out.println("Enter a string value ::");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();

      System.out.println("Enter a particular character ::");
      char character = sc.nextLine().charAt(0);
      int count = 0;

      for (int i=0; i<str.length(); i++){
         if(character == str.charAt(i)){
            count++;
         }
      }
      System.out.println("Frequency of the give character:: "+count);
   }
}

Output

Enter a string value ::
Hi welcome to Tutorialspoint
Enter a particular character ::
t
Frequency of the give character:: 3

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements