当前位置: 代码迷 >> Web前端 >> 统计付出的字符串中出现次数最多的字符
  详细解决方案

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

热度:71   发布时间:2012-08-24 10:00:21.0
统计给出的字符串中出现次数最多的字符
package com.flywater.sf;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public class FirstRabbit

             /**
     * 统计给出的字符串中出现次数最多的字符
     */
    public static void countCharacterInString(){ 
        int a = (int)(Math.random()*1000);
        System.out.println(a);
        String target = "hello world  what about you today";  
        char ch[] = target.toCharArray();
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for(Character c:ch){  
            if(Character.isWhitespace(c)) continue;  
            if(map.containsKey(c) == false){  
                map.put(c, 1);  
             }else{  
                 map.put(c, map.get(c)+1);  
             }  
        }  
        Set<Character> set = map.keySet();  
        Iterator iter = set.iterator();  
        Integer count=0;  
        Character key = new Character(' ');  
          
        while(iter.hasNext()){  
            Character ccc = (Character)iter.next();  
            System.out.println(ccc +": "+ map.get(ccc));  
            if(map.get(ccc) > count){  
                count = map.get(ccc);  
                key = ccc;  
            }  
        }  
          
        System.out.println(key.toString()+" "+ count);  
    }
    /**
     * 统计随机数出现最多的数字
     */
    public static void getRedom(){
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0;i<2000;i++) {
            Integer rm = new Integer((int)(Math.random()*20));
            if(map.containsKey(rm)==false) {
                map.put(rm, 1);
            } else {
                map.put(rm, +map.get(rm)+1);
            }
        }
        System.out.println(map);
    }
   
}
  相关解决方案