Write a program 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
Sample Input: Alphabets
Sample Output:==========================
Alphabet Frequency
==========================
a 2
b 1
e 1
h 1
l 1
p 1
s 1
t 1
import
java.io.*;
class
AlphabetFreq
{
public
static
void
main(String args[])
throws
IOException
{
BufferedReader br=
new
BufferedReader(
new
InputStreamReader(System.in));
System.out.print(
"Enter any string: "
);
String s = br.readLine();
s=s.toLowerCase();
//converting the string into lowercase
int
l=s.length();
//finding the length of the string
char
ch;
System.out.println(
"Output:"
);
System.out.println(
"=========================="
);
//this is just for styling the look of the output
System.out.println(
"Alphabet\tFrequency"
);
System.out.println(
"=========================="
);
/* Counting frequency of alphabets begins below */
int
count=
0
;
for
(
char
i=
'a'
; i<=
'z'
; i++)
{
count =
0
;
for
(
int
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);
}
}
}
}
Output:
Enter any string: ilovejavaforschool
Output:
==========================
Alphabet Frequency
==========================
a 2
c 1
e 1
f 1
h 1
i 1
j 1
l 2
o 4
r 1
s 1
v 2
No comments:
Post a Comment