10

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

4

3 回答 3

13

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();
于 2013-10-19T16:16:58.050 回答
8

您可以尝试寻找Collections.sort然后尝试这样:-

Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);

像这样的东西: -

private static Comparator<String> ALPHA_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int x = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (x== 0) {
            x= str1.compareTo(str2);
        }
        return x;
    }
};

Collections.sort(list, ALPHA_ORDER);

编辑:-

要在字符串中按字母顺序排序,请尝试如下:-

Collator col = Collator.getInstance(new Locale("en", "EN"));
String s = "AbaC";
String[] s1= s.split("");
Arrays.sort(s1, col);
String sorted = "";
for (int i = 0; i < s1.length; i++)
{
  sorted += s1[i];
}
System.out.println(sorted);
于 2013-10-19T16:16:36.423 回答
3

将 String 转换为字符数组,然后比较排序中每个字符的 int 值。

需要的方法: String.toCharArray();

于 2013-10-19T16:11:10.470 回答