统计字符串中字符出现的次数并输出,出现次数最多的字符
程序员文章站
2022-03-15 20:53:26
...
/**
* 输出字符串s中出现次数最多的字符
* @param s
*/
public void testMaxCount(String s){
char[]a=s.toCharArray();
Map<String, Integer> count=new HashMap<String, Integer>();
for(char c:a){
if(!count.containsKey(String.valueOf(c))){
count.put(String.valueOf(c), 1);
}else{
int i=count.get(String.valueOf(c))+1;
count.remove(String.valueOf(c));
count.put(String.valueOf(c), i);
}
}
Set<Entry<String, Integer>> ss=count.entrySet();
int max=0;
String maxName="";
for(Iterator<Entry<String, Integer>> it =ss.iterator();it.hasNext();){
Entry<String, Integer> o=it.next();
int value=o.getValue();
while(value>max){
max=value;
maxName=o.getKey();
}
}
System.out.println("出现次数最多的字符是:"+maxName+"出现了:"+max+"次");
}
上一篇: HashSet如何保证元素唯一性