Sort a String in Java (2 different ways)

String class doesn’t have any method that directly sort a string, but we can sort a string by applying other methods one after other.

Method 1(natural sorting) :

  1. Apply toCharArray() method on input string to create a char array for input string.
  2. Use Arrays.sort(char c[]) method to sort char array.
  3. Use String class constructor to create a sorted string from char array.

Note : As we know that String is immutable in java, hence in third step we have to create a new string.



Sort a String alphabetically :

Examples :

Input string : "geeksforgeeks"
Output string : "eeeefggkkorss"
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to sort a string alphabetically
  
import java.util.Arrays;
  
public class GFG 
{
    // Method to sort a string alphabetically
    public static String sortString(String inputString)
    {
        // convert input string to char array
        char tempArray[] = inputString.toCharArray();
          
        // sort tempArray
        Arrays.sort(tempArray);
          
        // return new sorted string
        return new String(tempArray);
    }
      
    // Driver method
    public static void main(String[] args)
    {
        String inputString = "geeksforgeeks";
        String outputString = sortString(inputString);
          
        System.out.println("Input String : " + inputString);
        System.out.println("Output String : " + outputString);
    }
}

chevron_right


Output:

Input String : geeksforgeeks
Output String : eeeefggkkorss

Arrays.sort(char c[]) method sort characters based on their ASCII value, we can define our custom Comparator to sort a string.

Method 2(custom sorting):

  1. Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.
  2. Use Arrays.sort(T [ ], Comparator c) method to sort Character array. For this, we must have to implement compare() method based on our custom sorting behavior.
  3. Now we can use StringBuilder to convert Character array to String.

Sort a mixed string(containing uppercase and lowercase characters) :

Examples :

Input String : GeeksforGeeks
Output String : eeeefGGkkorss
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to sort a mixed string
  
import java.util.Arrays;
import java.util.Comparator;
  
public class GFG 
{
    // Method to sort a mixed string
    public static String sortString(String inputString)
    {
        // convert input string to Character array
        Character tempArray[] = new Character[inputString.length()];
        for (int i = 0; i < inputString.length(); i++) {
            tempArray[i] = inputString.charAt(i);
        }
          
          
        // Sort, ignoring case during sorting
        Arrays.sort(tempArray, new Comparator<Character>(){
  
            @Override
            public int compare(Character c1, Character c2)
            {
                // ignoring case
                return Character.compare(Character.toLowerCase(c1),
                                        Character.toLowerCase(c2));
            }
        });
          
        // using StringBuilder to convert Character array to String
        StringBuilder sb = new StringBuilder(tempArray.length);
        for (Character c : tempArray)
            sb.append(c.charValue());
  
        return sb.toString();
    }
      
    // Driver method
    public static void main(String[] args)
    {
        String inputString = "GeeksforGeeks";
        String outputString = sortString(inputString);
          
        System.out.println("Input String : " + inputString);
        System.out.println("Output String : " + outputString);
    }
  
}

chevron_right


Output:

Input String : GeeksforGeeks
Output String : eeeefGGkkorss

Note :

public int compare(Object o1, Object o2)
{
     // have to return -ve if o1 has to come before o2
     // have to return +ve if o1 has to come after o2
     // have to return 0 if o1 is equal to o2
}

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up