Sort a single String in Java

后端 未结 10 928
误落风尘
误落风尘 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:49

    Convert to array of chars → Sort → Convert back to String:

    String s = "edcba";
    char[] c = s.toCharArray();        // convert to array of chars 
    java.util.Arrays.sort(c);          // sort
    String newString = new String(c);  // convert back to String
    System.out.println(newString);     // "abcde"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 18:53

    Question: sort a string in java

    public class SortAStringInJava {
        public static void main(String[] args) {
    
            String str = "Protijayi";
    // Method 1
            str = str.chars() // IntStream
                    .sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
    
            System.out.println(str);
            // Method 2
            str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
            System.out.println(str);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 18:57
        String a ="dgfa";
        char [] c = a.toCharArray();
        Arrays.sort(c);
        return new String(c);
    

    Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase). You can pass a comparator to the Sort method to change that.

    0 讨论(0)
提交回复
热议问题