Sort a single String in Java

后端 未结 10 927
误落风尘
误落风尘 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:33
    public static void main(String[] args) {
        String str = "helloword";   
        char[] arr;
        List<Character> l = new ArrayList<Character>();
        for (int i = 0; i < str.length(); i++) {
            arr = str.toCharArray();
            l.add(arr[i]);
    
        }
        Collections.sort(l);
        str = l.toString();
        System.out.println(str);
        str = str.replaceAll("\\[", "").replaceAll("\\]", "")
                .replaceAll("[,]", "");
        System.out.println(str);
    
    }
    
    0 讨论(0)
  • 2020-11-28 18:36

    Without using Collections in Java:

    import java.util.Scanner;
    
    public class SortingaString {
        public static String Sort(String s1)
        {
            char ch[]=s1.toCharArray();         
            String res=" ";
            
            for(int i=0; i<ch.length ; i++)
            {
                for(int j=i+1;j<ch.length; j++)
                {
                    if(ch[i]>=ch[j])
                    {
                        char m=ch[i];
                        ch[i]=ch[j];
                        ch[j]=m;
                    }
                }
                
                res=res+ch[i];
                
            }
    
            return res;
        }
    
        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("enter the string");
            
            String s1=sc.next();
            String ans=Sort( s1);
            
            System.out.println("after sorting=="+ans);
        }
    }
    

    Output:

    enter the string==

    sorting

    after sorting== ginorst

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

    A more raw approach without using sort Arrays.sort method. This is using insertion sort.

    public static void main(String[] args){
        String wordSt="watch";
        char[] word=wordSt.toCharArray();
    
        for(int i=0;i<(word.length-1);i++){
            for(int j=i+1;j>0;j--){
                if(word[j]<word[j-1]){
                    char temp=word[j-1];
                    word[j-1]=word[j];
                    word[j]=temp;
                }
            }
        }
        wordSt=String.valueOf(word);
        System.out.println(wordSt);
    }
    
    0 讨论(0)
  • 2020-11-28 18:46

    No there is no built-in String method. You can convert it to a char array, sort it using Arrays.sort and convert that back into a String.

    String test= "edcba";
    char[] ar = test.toCharArray();
    Arrays.sort(ar);
    String sorted = String.valueOf(ar);
    

    Or, when you want to deal correctly with locale-specific stuff like uppercase and accented characters:

    import java.text.Collator;
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.Locale;
    
    public class Test
    {
      public static void main(String[] args)
      {
        Collator collator = Collator.getInstance(new Locale("fr", "FR"));
        String original = "éDedCBcbAàa";
        String[] split = original.split("");
        Arrays.sort(split, collator);
        String sorted = "";
        for (int i = 0; i < split.length; i++)
        {
          sorted += split[i];
        }
        System.out.println(sorted); // "aAàbBcCdDeé"
      }
    }
    
    0 讨论(0)
  • 2020-11-28 18:47

    Procedure :

    1. At first convert the string to char array
    2. Then sort the array of character
    3. Convert the character array to string
    4. Print the string

    Code snippet:

        String input = "world";
        char[] arr = input.toCharArray();
        Arrays.sort(arr);
        String sorted = new String(arr);
        System.out.println(sorted);
    
    0 讨论(0)
  • 2020-11-28 18:49

    In Java 8 it can be done with:

    String s = "edcba".chars()
        .sorted()
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
    

    A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:

    String sorted =
        Stream.of("edcba".split(""))
            .sorted()
            .collect(Collectors.joining());
    
    0 讨论(0)
提交回复
热议问题