字符串排序

public class Test {

    public static void main(String[] args) {
        String[] array = {"D","B","A","C"};
        //sort(array);
        shortStr("BDAC");
    }
    /**
     * 方法 一:数组排序返回字符串
     * @param array
     */
    public static void sort(String[] array) {
        int len = array.length;
        String temp = null;
        for (int i = 0; i < len - 1; i++) {
            for (int j = 0; j < len - 1 - i; j++) {
                if ((array[j].compareTo(array[j + 1])) > 0) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        
        StringBuffer s=new StringBuffer();
        for (String str : array) {
            s.append(str);
        }
        System.out.println("结果是:"+s);
    }
    /**
     * 方法二:字符串排序返回字符串
     */
    public static void shortStr(String str){
        
        char[] c =str.toCharArray();
        char temp = '_';
        for (int i = 0; i < c.length; i++) {
            for (int j = 0; j < c.length-i-1; j++) {
                if (c[j]>c[j+1]) {
                    temp = c[j];
                    c[j] = c[j+1];
                    c[j+1]=temp;
                }
            }
        }

     StringBuffer s = new StringBuffer();
for (int i = 0; i < c.length; i++) { s.append(c[i]); } System.out.println("结果是:"+s); } /** * 字符转换 * @param str * @return */ public String[] getLongStrings(String str){ String[] strs = str.split(""); String[] ss = new String[strs.length-1]; for (int i = 0; i < ss.length; i++) { ss[i] = strs[i+1]; } return ss; } public String[] getShotStrings(String str){ char[] cs = str.toCharArray(); String[] ss=new String[cs.length]; for (int i = 0; i < ss.length; i++) { ss[i] = cs[i]+""; } return ss; } }
原文地址:https://www.cnblogs.com/zhaojinhui/p/4043893.html