从命令行上输入一组字符,输出各个字母的有多少
请输入字符串:
    hello world gamecolloege
    结果:
    h 1
    e 4
    l 5
    o 4
    等等     
请问这里该怎么做最好,最快,用switch来判断是在太慢了!

解决方案 »

  1.   

    可以用charAt()这个方法来试试看!!!!
      

  2.   

    如果单纯的统计字母,程序如下:public class Tongji {
        
        public static void main(String[] args) {
            // TODO code application logic here
            String str="ABabcdefgxyzXYZ";
            int len=str.length();
            int a[]=new int[200];
            char ch;
            for (int i=0;i<len;i++){
                ch=str.charAt(i);
                a[(int)ch]++;
            }
            for (int i=65;i<=200;i++){
                ch=(char)i;
                if (a[i]>0) System.out.println(ch+":"+a[i]);
            }
            
        }
        
    }我就不讲解了,呵呵,能跑,调试过了
      

  3.   

    设两个数组,一个存字母,一个存字母的个数。
    用charAt()得到一个字母,和字母数组比较,用indexOf()查找,如果没有找到的话会返回-1,
    如果没有找到的话,把这个字母存入字母数组,对应的(相同)字母个数数组中初始化为1。
    如果找到了,返回index,把对象的字母个数数组中的数字加1。大概就是这个样子:
    tmpChar = args[i].charAt(j);
    tmpIndex=indexOf(tChar);
    if(tmpIndex!=-1)
       count[tmpIndex-]+=1;
    else
       later[index-1]=tChar;
       count[index-1]=1;
       index++;
      

  4.   

    简单,代码如下:import java.util.HashMap;
    import java.util.Iterator;public class Exercise {    public static void main(String[] args) {
            HashMap map = getCharMount(args[0]);        //打印结果
            Iterator it = map.keySet().iterator();
            while (it.hasNext()) {
                Object ch = it.next();
                System.out.println(ch + " " + map.get(ch));
            }
        }    /**
         * 将字符串str中的字符及其出现的次数存入HashMap
         */
        public static HashMap getCharMount(String str) {
            HashMap map = new HashMap();
            for (int i = 0; i < str.length(); i++) {
                Character ch = new Character(str.charAt(i));
                Integer tmp = (Integer) map.get(ch);
                if (tmp == null)
                    map.put(ch, new Integer(1));
                else
                    map.put(ch, new Integer((tmp.intValue() + 1)));
            }
            return map;
        }
    }
      

  5.   

    njwangchuan(川儿) 以及 ponent2005(沧浪之水清兮) 的代码都有它的局限性, 应该运用java中的API:java.util.HashMap
      

  6.   

    谢谢各位大哥了,我自己琢磨琢磨!!!我爱CSDN!!