计算数组中元素的出现 [英] count occurrence of element in array
问题描述
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)
此
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);
}
}
但是我得到了:
4
3
2
2
1
2
1
1
我的错在哪里?
推荐答案
问题是您正在为字符串中的每个字符创建一个新计数器,而不是为每个可能的字母创建一个计数器。本质上,您的程序会计算一个字符在当前字符之后的位置中出现在字符串中的次数。
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]);
}
}
}
这篇关于计算数组中元素的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!