如何按字母顺序对字符串进行排序java


问题内容

我想按字母顺序对JAVA中的字符串进行排序,如下所示:AaBbCcDdEeFfGg之后是大写字母和小写字母。例如,如果我把AbaC退还给我AabC,谢谢!


问题答案:

Arrays.sort如果先将字符放入数组中,则可以使用进行此操作。(为了使用不区分大小写的自定义比较器,它必须是Character对象数组,而不是char基元。)

// put the characters into an array
Character[] chars = new Character[str.length()];
for (int i = 0; i < chars.length; i++)
    chars[i] = str.charAt(i);

// sort the array
Arrays.sort(chars, new Comparator<Character>() {
    public int compare(Character c1, Character c2) {
        int cmp = Character.compare(
            Character.toLowerCase(c1.charValue()),
            Character.toLowerCase(c2.charValue())
        );
        if (cmp != 0) return cmp;
        return Character.compare(c1.charValue(), c2.charValue());
    }
});

// rebuild the string
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
str = sb.toString();