需求:取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)... 
 
两种方法写的 大家一起来看看还有其他方法没有? 
-  import java.util.*;
 
  
- public class Test1 {
 
  
-         public static void main(String[] args) {
 
 -                 String str = "abcdekka27qoq";
 
 -                 PanDuan(str);
 
 -                 //useMapPanDuan(str);
 
 -                 
 
 -         }
 
 -         
 
 -         public static void PanDuan(String str){
 
 -                 int i = 0,x=0,y,m;
 
 -                 for(y='a'; y<='z'; y++){
 
 -                         m=-1;
 
 -                         do {
 
 -                                 x = str.indexOf(y, i);
 
 -                                 i=x+1;
 
 -                                 m++;
 
 -                                 //System.out.println("m="+m+",i="+i+",x="+x);
 
 -                         } while (x!=-1);
 
 -                         if(m!=0){
 
 -                                 System.out.print((char)y+"("+m+")");
 
 -                         }
 
 -                         
 
 -                 }
 
 -                 System.out.println("");
 
 -         }
 
 -         public static void useMapPanDuan(String str){
 
 -                 TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
 
 -                 char[] chs = str.toCharArray();
 
 -                 Set<Character> s = tm.keySet();
 
 -                 for(Character ch:chs){
 
 -                         if(ch>='0'&&ch<='9')
 
 -                                 continue;
 
 -                         Integer i = tm.get(ch);
 
 -                         if(i==null){
 
 -                                 tm.put(ch,1);
 
 -                         }else{
 
 -                                 tm.put(ch,i+1);
 
 -                         }
 
 -                 }
 
 -                 StringBuilder sb = new StringBuilder();
 
 -                 for(Character ch1: s){
 
 -                         sb.append(ch1).append("(").append(tm.get(ch1)).append(")");
 
 -                 }
 
 -                 System.out.println(sb);
 
 -         }
 
 - }
 
  复制代码 |   
        
 
    
    
    
     
 
 |