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

33,081

Solution 1

char[] chars = theWord.toCharArray();
Arrays.sort(chars);
String newWord = new String(chars);

Solution 2

See Arrays.sort() & toCharArray()

Solution 3

Agreed, I stole the solution. But apparently, it's also important to strip whitespace and make everything lowercase:

char[] array = theWord.replaceAll("\\s+", "").toLowerCase().toCharArray();
Arrays.sort(array);
System.out.println(new String(array));

Solution 4

None of the above solutions are locale specific , therefore I came with this solution, it is not efficient , but it works very well..

public static String localeSpecificStringSort(String str, Locale locale) {

        String[] strArr = new String[str.length()];

        for(int i=0;i<str.length();i++){
            strArr[i] =  str.substring(i,i+1);
        }
        Collator collator = Collator.getInstance(locale);
        Arrays.sort(strArr, collator);
        StringBuffer strBuf = new StringBuffer();
        for (String string : strArr) {
            strBuf.append(string);
        }
        return strBuf.toString();
    }

Solution 5

char[] arr = new char[theWord.length()];
for(int i=0;i<theWord.length;i++)
{
    arr[i]=theWord.charAt(i);
}
for(int i=0;i<theWord.length();i++)
  for(int j=0;j<theWord.length();j++)
{
    char temp = arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}
int size=theWord.length();
theWord="";
for(int i=0;i<size;i++)
{
    theWord+=arr[i];
}
Share:
33,081
randomizertech
Author by

randomizertech

All over the continent (from Greenland to Chile, and vice-versa)

Updated on October 16, 2020

Comments

  • randomizertech
    randomizertech over 3 years

    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

  • Paul
    Paul almost 13 years
    Another homework assignment completed by Stack Overflow, in 4 minutes.
  • Sean Patrick Floyd
    Sean Patrick Floyd almost 13 years
    @Paul that's part of my job security scheme. By keeping future developers from thinking about their problems I also keep them from improving and eliminate potential competition :-)