Java Examples : Frequency of the character in a paragraph
softetechnologies
31-08-2017    1302 times
Character Frequency

Q. Write a program to display the frequency of the character in a paragraph using java.

Here accept a string from the user by the method nextLine(). which is found under the Scanner class of java.util package. now extract each character from it. if the character is alphabetic then increment the corresponding counter. Now print those counters one after another. The details 


import java.util.*;
class FrequencyChar
{
public static void main(String []args)
{
String str;
int []arr=new int[26];
Scanner sc=new Scanner(System.in);
System.out.print("Enter Your Text Here : ");
str=sc.nextLine();
str=str.toUpperCase();
char ch;
for(int i=0;i<str.length();i++)
{
ch=str.charAt(i); 
if(ch>=65 && ch<=90)
arr[ch-65]++;
}
for(int j=0;j<26;j++)
{
if(arr[j]>0)
System.out.println(((char)(j+65)) + " : " + arr[j]);
}
}
}

Private Teacher

Here we take an integer array of length 26. Indexes of this array represent the character A-Z. That is Index 0 is represent A, Index 1 represents B, Index 2 represents C …… and so on.

  • Convert our text into the upper case using the toUpperCase() method.
  • Extract each character from the string. If that Character is alphabet that is ASCII code within 65 -90. Then increase the value of the corresponding index value. Calculate the index as follows
    • If Character A then ASCII code is 65. The array index will be 65-65=0.
    • Now print only those array elements which values are not zero.
softetechnologies
softetechnologies
    Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
    Related Post
  Query About the post