在 Java 中对单个字符串进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/605891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:47:05  来源:igfitidea点击:

Sort a single String in Java

javastringsorting

提问by

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

有没有一种本地方法可以按 Java 中的内容对字符串进行排序?例如

String s = "edcba"  ->  "abcde"

回答by Jon Skeet

toCharArrayfollowed by Arrays.sortfollowed by a String constructor call:

toCharArray后跟Arrays.sort一个 String 构造函数调用:

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.

编辑:正如tackline所指出的,如果字符串包含代理对或复合字符(重音+ e作为单独的字符)等,这将失败。在这一点上它变得更加困难......希望你不需要这个:)此外,这只是按序数排序,没有考虑大小写、重音或其他任何因素。

回答by eljenso

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 方法。您可以将其转换为字符数组,使用 Arrays.sort 对其进行排序并将其转换回字符串。

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é"
  }
}

回答by amit

    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.

请注意,如果它是大小写混合的字符串(它将大写放在小写之前),则这将无法按预期工作。您可以将比较器传递给 Sort 方法来改变它。

回答by agaase

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

一种更原始​​的方法,不使用 sort Arrays.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);
}

回答by Maroun

Convert to array of charsSortConvert 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"

回答by Marcin

In Java 8 it can be done with:

在 Java 8 中,它可以通过以下方式完成:

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:

与长度为 1 的字符串流(未排序的字符串中的每个字符都转换为流中的字符串)一起使用的稍短的替代方法是:

String sorted =
    Stream.of("edcba".split(""))
        .sorted()
        .collect(Collectors.joining());

回答by rashedcs

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
  1. 首先将字符串转换为字符数组
  2. 然后对字符数组进行排序
  3. 将字符数组转换为字符串
  4. 打印字符串

Code snippet:

代码片段:

    String input = "world";
    char[] arr = input.toCharArray();
    Arrays.sort(arr);
    String sorted = new String(arr);
    System.out.println(sorted);

回答by Tarun Jadhav

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);

}

回答by naveen prasanna

Without using Collections in Java:

在 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

输入字符串==

排序

排序后== ginorst

回答by Soudipta Dutta

Question: sort a string in java

问题:在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);
    }
}