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

Object Oriented ProgrammingJava Programming Java8

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
raja
Published on 26-Apr-2018 12:58:03
Advertisements