黑马程序员技术交流社区

标题: 求详细解答 [打印本页]

作者: dengxuye    时间: 2016-3-31 18:40
标题: 求详细解答
取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,
输出格式为:a(2)b(1)k(2)...


作者: 11210107    时间: 2016-3-31 20:04
本帖最后由 11210107 于 2016-3-31 20:11 编辑

自己写的,可能有点麻烦。
public static String getCharTimes(String string){
                String str = "";                //返回的字符串
                int count;                                //计数器
                char c;
                for(int i = 0;i < string.length();i++){
                        count = 0;
                        c = string.charAt(i);
                        if((c < 97 && c>=65) || (c >= 97&&c <= 122)){
                                
                                for(int j = 0;j < string.length();j++){
                                        if(c == string.charAt(j)){
                                                count++;
                                        }
                                }
                                if(str.indexOf(c) != -1){ //如果待返回字符串str已经存在该字符c,结束当前循环避免重复。
                                        continue;
                                }
                                str += c + "("+count+")";
                        }
                }
                return str;
        }
作者: 15507596326    时间: 2016-3-31 21:43
public static void main(String[] args) {
        String str="abcdekka27qoq";
        char[] arr = str.toCharArray();
        TreeMap<Character,Integer> t=new TreeMap<>();
        for (Character c : arr) {
            Integer i = t.get(c);
            i=!t.containsKey(c)?1:i+1;
            t.put(c, i);
        }
        for (char c : t.keySet()) {
            System.out.print(c+"("+t.get(c)+")");
        }
    }





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2