Is there a native way to sort a String by its contents in java? E.g.
String s = "edcba" -> "abcde"
Is there a native way to sort a String by its contents in java? E.g.
String s = "edcba" -> "abcde"
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.
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é"
}
}
Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase)
Why wouldn't you expect a sequence of numbers to be sorted by their numerical value unless you specify otherwise?