JAVA算法字符串统计

来源:互联网 发布:织梦网站数据采集器 编辑:程序博客网 时间:2024/05/22 07:45
 String s="asdsdfsdfasdasda";           int differentCount = 0;           Map<Character,Integer> map = new HashMap<Character,Integer>();           for(int i=0;i<s.length();i++){               Character c = new Character(s.charAt(i));               if(map.containsKey(c)){                   map.put(c, map.get(c).intValue()+1);               }else{                   map.put(c, new Integer(1));               }           }           Iterator<Character> it = map.keySet().iterator();           while(it.hasNext()){               Character tmpc = it.next();               differentCount++;               System.out.println(tmpc+"="+map.get(tmpc));           }           System.out.println("differentCount="+differentCount);  -------------------------------------------------------------------------

方法2
/*   * To change this template, choose Tools | Templates   * and open the template in the editor.   */    package mysrc;     import java.util.*;   /**   *   * @author yunchow   */  public class Test {              public static void  main(String[] args){           char[] c = "asdsdfsdfasdasda".toCharArray();           List<T> list = new ArrayList<T>();           for(int i=0;i<c.length;i++){               if(!list.contains(new T(c[i])))                   list.add(new T(c[i],1));               else{                   T t = new T(c[i]);                   for(int j=0;j<list.size();j++){                       if(t.equals(list.get(j))){                           t = list.get(j);                           t.setN(t.getN()+1);                       }                   }               }           }           for(int t=0;t<list.size();t++){               T tt = new T();               tt = list.get(t);               System.out.println("The Char is : " + tt.getC() + ", The Num is : " + tt.getN());           }       }   }   class T {       private char c;       private int n;       public T(){}       public T(char a){           c = a;       }       public T(char a,int m){           c = a;           n = m;       }       public void setC(char arg){           c = arg;       }       public char getC(){           return c;       }       public void setN(int arg){           n = arg;       }       public int getN(){           return n;       }         @Override      public int hashCode() {           return this.c;       }         @Override      public boolean equals(Object obj) {           return this.hashCode() == obj.hashCode();       }          }  

原创粉丝点击