日期:2014-05-19  浏览次数:20676 次

字符串的处理
如何把字符串 String str="01,01,02,03,03,10";
处理为:
  String StrTwo ="0102,2001,0302,1001"; (4位中前两位标识字符串,后两位表示重复次数。如0102表示有02个01)

------解决方案--------------------
Java code

Map<String,Integer> map=new HashMap<String,Integer>();
        String str="01,01,02,03,03,10";
        String[] ss=str.split(",");
        for(String s:ss){
            Integer count=map.get(s);
            if(count==null){
                map.put(s, 1);
            }else{
                map.put(s, count+1);
            }
        }
        String result="";
        for(Entry<String,Integer> e:map.entrySet()){
            if(!"".equals(result)){
                result+=",";
            }
            result+=(e.getKey()+(e.getValue()<10?("0"+e.getValue()):e.getValue()));
        }
        System.out.println(result);

------解决方案--------------------
Java code


package a;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test5 {

    /**
     * @param args
     * @author sunstar
     * @date 2012-7-18 下午5:29:53
     */
    public static void main(String[] args) {
        String str ="01,01,02,03,03,10";

        Map<String, Integer> map = new HashMap<String, Integer>() ;
        String arrs[] = str.split(",") ;
        String tmp = "" ;
        int num = 0 ;
        for (int i = 0; i < arrs.length; i++){
            tmp = arrs[i] ;
            if (map.get(tmp) != null){
                num = map.get(tmp)+ 1 ;
            }else
                num = 1 ;
            map.remove(tmp) ;
            map.put(tmp, num) ;
            
            
        }
        
        Iterator it = map.keySet().iterator() ;
        StringBuffer sb = new StringBuffer() ;
        while(it.hasNext()){
            tmp = (String) it.next() ;
            sb.append(intToFormatStr(map.get(tmp), 2) +tmp ) ;
            sb.append(",") ;
            System.out.println(tmp + " --" + map.get(tmp)+"次") ;
        }
        System.out.println(sb.toString().substring(0,sb.toString().length()-1)) ;

    }
    public static String intToFormatStr(int value, int len){
        String str = value +"";
        while(str.length() < len){
            str = "0" + str ;
        }
        return str ;
    }

}