A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 18263368378 中级黑马   /  2016-4-25 22:49  /  325 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

已知字符串"aababcabcdabcde"。
获取字符串中每一个字母出现的次数。
要求结果:a(5)b(4)c(3)d(2)e(1)
代码如下:
package kehouzuoye25_1;

import java.util.Set;
import java.util.TreeMap;

public class Hqcs {
        public static void main(String[] args) {
                String s = "aababcabcdabcde";
                char[] c = s.toCharArray();
                TreeMap<Character, Integer> h = new TreeMap<Character, Integer>();
                for (char d : c) {
                        if(h.containsKey(d)){
                                int sum = h.get(d)+1;
                                h.put(d, sum);
                        }else{
                                h.put(d, 1);
                        }
                }
                Set<Character> st = h.keySet();
                for (Character cha : st) {
                        System.out.print(cha+"("+h.get(cha)+")");
                }
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马