Creating new String with sorted letters from a String word in Java

randomizertech picture randomizertech · Jun 7, 2011 · Viewed 32.6k times · Source

How do I create a String with alphabetical order letters taken from another String?

Let's say I have something like this

String theWord = "Hello World";

How do I compute the new String to make it look like"

dehllloorw

Which is theWord but sorted character by character in alphabetical order.

Thanks in advance

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Jun 7, 2011
char[] chars = theWord.toCharArray();
Arrays.sort(chars);
String newWord = new String(chars);