Sort a single String in Java

后端 未结 10 934
误落风尘
误落风尘 2020-11-28 18:15

Is there a native way to sort a String by its contents in java? E.g.

String s = \"edcba\"  ->  \"abcde\"
10条回答
  •  温柔的废话
    2020-11-28 18:51

    toCharArray followed by Arrays.sort followed by a String constructor call:

    import java.util.Arrays;
    
    public class Test
    {
        public static void main(String[] args)
        {
            String original = "edcba";
            char[] chars = original.toCharArray();
            Arrays.sort(chars);
            String sorted = new String(chars);
            System.out.println(sorted);
        }
    }
    

    EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.

提交回复
热议问题