char [] array = {a,a,a,b,b,c,c,c,a,d};
I want to count every same element in that array so I can sort it from highest frequency to the lowest one. I want the output become like this:
4 (for a)
2 (for b)
3 (for c)
1 (for d)
I have try this
public static void CountbyChar(String s){
int [] arr = new int [s.length()];
char [] c =s.toCharArray();
for (int i=0;i<c.length;i++){
arr[i]=1;
for (int j=i+1;j<c.length;j++){
if(c[i]==c[j]){
arr[i]++;
}
}
}
for (int x:arr){
System.out.println(x);
}
}
But I got:
4
3
2
2
1
2
1
1
Where is my fault?
The problem is that you are creating a new counter for each character in the string, rather than creating one for each possible letter. Essentially, your program counts how many times a character occurs in a string in positions after the current character.
Fixing this issue should be relatively easy: make counters for each letter of the alphabet, and increment them when you see the corresponding letter. Assuming that you do it case-sensitively, you can do it like this:
public static void CountbyChar(String s){
int [] arr = new int [256];
for (char c : s.toCharArray()){
if (c < 256) {
arr[c]++;
}
}
for (int i = 0 ; i != 256 ; i++) {
if (arr[i] != 0) {
System.out.print((char)i);
System.out.print(" : ");
System.out.println(arr[i]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With