Dark mode logo
Last Updated:
Frequency of a character in a string

Frequency of a Character in a string using java

Algorithm

Input: Input the string and the character to find the frequency.
Output: The frequency of the entered character is displayed.
1.Start
2.count=0,i=0
3.Read a string and store it in str
4.Find the length of the string and store it in len
5.Read the character to find the frequency and store it in ch
6.while (i<len)
  6.1.if(str.charAt(i) = = ch.charAt(0))
    6.1.1.count++ 6.2.i++
7.Print "The frequency of the character is:" +count
8.Stop

Java Program

import java.util.Scanner;
public class Main {
        public static void main ( String[ ] args) {
           int count=0,i=0;
            Scanner reader = new Scanner(System.in);
           System.out.printf("Enter the string:");
            String str=reader.nextLine();
            int len=str.length();
            System.out.printf("Enter the character to get the frequency:");
            String ch = reader.nextLine();
            while (i<len) {
             if(str.charAt(i) == ch.charAt(0)) {
                count++;
              }
              i++;
            }
           System.out.printf("The frequency of "+ch+" is: "+count);
        }
    }

Output

Enter the string: Hello
Enter the character to get the frequency: l
The frequency of l is 2

Comments