Let’s see a program to count the frequency of each character for a given string.
package program;
public class CountFrequencyExample {
public static void main(String[] args) {
String s = "bangalore";
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
int index = i;
int count = 0;
for (int j = 0; j < c.length; j++) {
if (j < i && (c[j] == c[i])) {
break;
}
if (c[index] == c[j]) {
count++;
}
}
if (count > 0) {
System.out.println(c[i] + " ---- " + count);
}
}
}
}
Output is :-
b —- 1
a —- 2
n —- 1
g —- 1
l —- 1
o —- 1
r —- 1
e —- 1