In this tutorial, we will write a program to calculate the frequency of Characters present in a String in java.
Frequency refers to the number of times that have occurred. In this program, we will count how many times each character is repeated in a String and display the result for each word’s frequency.
The program splits each word with space count present after every word, toCharArray()
function is used in the following java program.
Although if you want to know about the String and loop that are used in the program below. you may click the link below:
We will see two examples:
1. Where the String is already defined in the program.
2. Where the string is taken as an input from the user.
1. Program to find the frequency of Words in Java
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 | //find a frequency of a character public class FrequencyOfCharacter { public static void main(String[] args) { int i, j; String str = "Beautiful Beach"; int[] frequency = new int[str.length()]; char string[] = str.toCharArray(); for (i = 0; i < str.length(); i++) { frequency[i] = 1; for (j = i + 1; j < str.length(); j++) { if (string[i] == string[j]) { frequency[i]++; //Set string[j] to 0 string[j] = '0'; } } } //Displays the characters with their frequency System.out.println("Following Lists the characters and their frequency:"); for (i = 0; i < frequency.length; i++) { if (string[i] != ' ' && string[i] != '0') System.out.println(string[i] + "->" + frequency[i]); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 | Following Lists the characters and their frequency: B->2 e->2 a->2 u->2 t->1 i->1 f->1 l->1 c->1 h->1 |
2. Program to find the frequency of Words in Java, user’s input
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 41 42 43 44 | //find a frequency of a character import java.util.Scanner; public class FrequencyOfCharacter { public static void main(String[] args) { int i, j; String str; Scanner sc = new Scanner(System.in); //User Input System.out.println("Enter a string: "); str = sc.nextLine(); int[] frequency = new int[str.length()]; char string[] = str.toCharArray(); for (i = 0; i < str.length(); i++) { frequency[i] = 1; for (j = i + 1; j < str.length(); j++) { if (string[i] == string[j]) { frequency[i]++; //Set string[j] to 0 string[j] = '0'; } } } //Displays the characters with their frequency System.out.println("Following Lists the entered characters and their frequency:"); for (i = 0; i < frequency.length; i++) { if (string[i] != ' ' && string[i] != '0') System.out.println(string[i] + "->" + frequency[i]); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter a string: Beautiful Beach Following Lists the characters and their frequency: B->2 e->2 a->2 u->2 t->1 i->1 f->1 l->1 c->1 h->1 |