Wednesday 27 January 2016

Write a program in java to input a string (word). Convert it into lowercase letters. Count and print the frequency of each alphabet present in the string.

The output should be given as:
Sample Input: Alphabets
Sample Output:
==========================
Alphabet             Frequency
==========================
a                              2
b                              1
e                              1
h                              1
l                               1
p                              1
s                              1
t                              1

Code:
import java.util.*;
class AlphabetFreq
{
    public static void main(String args[])
    {
      String s;
      int l,count=0,j;
      char ch,i;
      Scanner sc=new Scanner(System.in);
      System.out.print("Enter any string: ");
      s = sc.nextLine();
      s=s.toLowerCase(); //converting the string into lowercase
      l=s.length(); //finding the length of the string
       /* Counting frequency of alphabets begins below */
          for(i='a'; i<='z'; i++)
            {
                count = 0;
                for(j=0; j<l; j++)
                {
                    ch=s.charAt(j); //extracting characters of the string one by one
                    if(ch==i) //first checking the whole string for 'a', then 'b' and so on
                count++; //increasing count of those aplhabets which are present in the string
                }
                if(count!=0)//printing only those alphabets whose count is not '0'
                {
                    System.out.println(i+"\t\t"+count);
                }
            }
    }

No comments:

Post a Comment