- //方法1,用集合
- String s = "bcdabncd";
- //定义map容器,键是字符,值是次数.
- HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
- char[] arr = s.toCharArray();
- for (char c : arr) {
- //如果map容器中不存在键,则将键存入到容器中,值为1.
- if (hm.get(c) == null)
- hm.put(c, 1);
- //如果map容器中存在键,则提取该键的值,并加1次.
- else
- hm.put(c, hm.get(c) + 1);
- }
- //迭代map容器
- Set<Entry<Character, Integer>> entrySet = hm.entrySet();
- Iterator<Entry<Character, Integer>> it = entrySet.iterator();
- while (it.hasNext()) {
- Entry<Character, Integer> en = it.next();
- Character key = en.getKey();
- Integer value = en.getValue();
- System.out.print(key + "[" + value + "]");
- }
- //方法2,用空字符替代指定字符,计算先后长度缩减的量,就是出现的次数.
- String s = "bcdabncd";
- while (s.length() > 0) {
- //取第一个字符.
- String str = s.substring(0, 1);
- //用空字符(不是空格字符)替代所有的指定字符.
- String s2 = s.replaceAll(str, "");
- //计算长度缩减的值
- int times = s.length() - s2.length();
- System.out.print(str + "[" + times + "]");
- //用被空字符替换后的字符串,取代之前的字符串,继续下一次循环.
- s = s2;
- }
复制代码
|