统计一个字符串中出现次数最多的字符

来源:互联网 发布:淘宝账号是不是会员名 编辑:程序博客网 时间:2024/05/29 08:30
  1. public void countCharacterInString(){  
  2.     String target = "hello world  what about you today";  
  3.     //将包含的字符放入哈希表,字符作为key,出现次数作为value  
  4.     char[] alph = target.toCharArray();  
  5.     Map<Character,Integer> aa = new HashMap<Character,Integer>();  
  6.     for(Character c:alph){  
  7.         if(Character.isWhitespace(c)) continue;  
  8.         if(aa.containsKey(c) == false){  
  9.              aa.put(c, 1);  
  10.          }else{  
  11.              aa.put(c, aa.get(c)+1);  
  12.          }  
  13.     }  
  14.     //比较获取出现最多次数的字符  
  15.     Set<Character> set = aa.keySet();  
  16.     Iterator iter = set.iterator();  
  17.     Integer count=0;  
  18.     Character key = new Character(' ');  
  19.       
  20.     while(iter.hasNext()){  
  21.         Character ccc = (Character)iter.next();  
  22.         System.out.println(ccc +": "+ aa.get(ccc));  
  23.         if(aa.get(ccc) > count){  
  24.             count = aa.get(ccc);  
  25.             key = ccc;  
  26.         }  
  27.     }  
  28.       
  29.     System.out.println(key.toString()+" "+ count);  

阅读全文
0 0
原创粉丝点击