forked from Mhassanbughio/Java-Small-Projects
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FrequencyOfCharacters
40 lines (32 loc) · 1.33 KB
/
FrequencyOfCharacters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
Given a string, this program prints the characters and their frequencies in alphabetical order
*/
import java.util.Scanner;
public class FrequencyOfCharacters {
public static void main(String[] args) {
int max = 26;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to find the frequencies of its characters:");
// Replaces all the substrings except(^) from characters a-z with the space character and converts them to lower case
String user_str = in.nextLine().toLowerCase().replaceAll("[^a-z]"," ");
int[] freq = new int[max];
char[] string = user_str.toCharArray();
int i,j;
for( i=0; i<user_str.length(); i++){
if(string[i] != ' ') {
freq[user_str.charAt(i) - 'a']++; // use the ascii code so that a-z have values 0 - 25
}
}
// Print the frequencies of the characters in alphabetical order
System.out.println("Characters and their corresponding frequencies:");
for(i = 0; i<max; i++) {
if( freq[i]!=0) {
System.out.print((char)(i+'a') + " - " +freq[i] + " ");
for (j = 0; j < freq[i]; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
}