到目前为止,这是我尝试过的:
public class CharacterCounter {
public static void main(String[] args){
String string = "sashimi";
int count = 0;
for(int i =0; i < string.length(); i++){
if(string.charAt(i) == 'i'){
count++;
}
}
System.out.println("The number of letter i is " + count);
}
}
输出:
The number of letter i is 2
但是我想做的是,该程序应该计算出出现次数最多的字符。
例如,这里的字符串是SASHIMI,输出应为:
the number of letter S is 2
the number of letter I is 2
我陷入了这个问题。我需要你的帮助。谢谢。
最佳答案
char[] chars = string.toCharArray();
HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();
for (char aChar : chars) {
if (countMap.containsKey(aChar)) {
countMap.put(aChar, countMap.get(aChar) + 1);
} else {
countMap.put(aChar,1);
}
}
//determine max occurence
int max = 0;
for (Integer i: countMap.values()) {
if (max < i) {
max = i;
}
}
//print all satisfiying max occurrence
for (Map.Entry<Character, Integer> e: countMap.entrySet()) {
if (e.getValue() == max) {
System.out.println("The number of letter " + e.getKey() + " is " + max);
}
}
关于java - Java中的字符计数器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17995021/