本帖最后由 anqi 于 2014-4-20 12:41 编辑
- public class Convert {
- public static void main(String[] args) {
- String str = "abcde%^kka27qoq";
- CountChar(str);
- }
- private static void CountChar(String str) {
- char[] c = str.toCharArray(); //转换为字符数组
- System.out.println(c);
- Map<Character,Integer> map = new LinkedHashMap<Character,Integer>(); //建立一个Map集合(因为map集合key相同会覆盖)
- for (int i = 0; i < c.length; i++) { //变量char[]数组
- if ((c[i] <= 90 && c[i] >= 65)||(c[i]>=97&&c[i]<=112)) { //判断只取字母
- //往集合里面添加
- if (!(map.keySet().contains(c[i]))) {
- map.put(c[i], 1); //第一次出现就添加一次
- } else {
- map.put(c[i], map.get(c[i]) + 1); //多次出现就取出出现的次数在加1后填入
- }
- }
- }
- //将集合里面的内容转换为字符串
- StringBuilder sb = new StringBuilder();
- Iterator<Map.Entry<Character,Integer>> it = map.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<Character,Integer> entry = it.next();
- sb.append(entry.getKey() + "(" + entry.getValue() + ")");
- }
- System.out.println(sb);
- }
- }
复制代码 |