统计字符串”abadcdffbaeba”中每个字符出现了多少次,按次数排序并输出


import java.util.*;
/**
* 统计字符串”abadcdffbaeba”中每个字符出现了多少次,按次数排序并输出
*/
public class Test {
    public static void main(String[] args) {
        String str = "abadcdffbaeba";
        Map tree = new TreeMap();
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                if (!tree.containsKey(ch)) {
                    tree.put(ch, new Integer(1));
                } else {
                    Integer in = (Integer) tree.get(ch) + 1;
                    tree.put(ch, in);
                }
            }
        }
        Iterator tit = tree.keySet().iterator();
        String aa[][] = new String[tree.size()][tree.size()];
        int jj = 0;
        while (tit.hasNext()) {
            Object temp = tit.next();
            System.out.print(temp.toString() + ":" + tree.get(temp) + ",");
            aa[jj][0] = temp.toString();
            aa[jj][1] = tree.get(temp).toString();
            jj++;
        }
        for (int i = 0; i < aa.length; i++) {
            for (int j = 0; j < aa.length - i - 1; j++) {
                if (Integer.parseInt(aa[j][1]) > Integer.parseInt(aa[j + 1][1])) {
                    String temp = aa[j][1];
                    aa[j][1] = aa[j + 1][1];
                    aa[j + 1][1] = temp;
                    String temp1 = aa[j][0];
                    aa[j][0] = aa[j + 1][0];
                    aa[j + 1][0] = temp1;
                }
            }
        }
        for (int i = 0, size = aa.length; i < size; i++) {
            System.out.println(aa[i][0] + "------" + aa[i][1]);
        }
    }
}


你可能感兴趣的:(java,统计字符串)