Friday, December 27, 2024
Google search engine
HomeLanguagesJavaSort a String in Java (2 different ways)

Sort a String in Java (2 different ways)

The string class doesn’t have any method that directly sorts a string, but we can sort a string by applying other methods one after another. The string is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.

Creating a String

There are two ways to create a string in Java:

  • String literal
String s = “Lazyroar”;
  • Using new keyword
String s = new String (“Lazyroar”);

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

Methods:

There exist two methods with which we can sort any string in java alphabetically

  1. Without using the sort() method
  2. By using the sort() method

Illustration:

Input string : "neveropen"
Output string : "eeeefggkkorss"

Now let us discuss methods and implement the same. 

Method 1: Without using the sort() method

Here we will be laying an approach to sort a string without using any predefined logic. So, it also does becomes an important approach from an interview perceptive view.

Procedure:

  1. Convert string to an array with the help of the toCharArray() method of the String class
  2. Now use nested loops to check for swapping elements of an array.
  3. Print these character array elements.

Example

Java




// Java program to Sort a String Alphabetically
// Using toCharArray() method
// Without using sort() method
 
// Importing required classes
import java.io.*;
import java.util.Arrays;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Custom string input
        String str = "neveropen";
       
        // Converting string into an array for computation
        char arr[] = str.toCharArray();
 
        // Nested loops for comparison of characters
        // in above character array
       
        char temp;
 
        int i = 0;
        while (i < arr.length) {
            int j = i + 1;
            while (j < arr.length) {
                if (arr[j] < arr[i]) {
                   
                    // Comparing the characters one by one
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
                j += 1;
            }
            i += 1;
        }
 
        // By now loop is done means we have
        // iterated the whole array
        System.out.println(arr);
    }
}


Output:

eeeefggkkorss

Method 2: By using the sort() method

2A By using the sort() method- natural sorting

Procedure:

  1. The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string.
  2. Now use Arrays.sort(char c[]) method to sort character array.
  3. Use the String class constructor to create a sorted string from a char array.

Example 1

Java




// Java program to Sort a String Alphabetically
// Using toCharArray() method
// With using the sort() method
 
// Importing Arrays class from java.util package
import java.util.Arrays;
 
// Main class
public class GFG {
    // Method 1
    // To sort a string alphabetically
    public static String sortString(String inputString)
    {
        // Converting input string to character array
        char tempArray[] = inputString.toCharArray();
 
        // Sorting temp array using
        Arrays.sort(tempArray);
 
        // Returning new sorted string
        return new String(tempArray);
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom string as input
        String inputString = "neveropen";
        String outputString = sortString(inputString);
 
        // Print and display commands
 
        // Input string
        System.out.println("Input String : " + inputString);
        // Output string
        System.out.println("Output String : "
                           + outputString);
    }
}


Output

Input String : neveropen
Output String : eeeefggkkorss

2B By using the sort() method- Custom sorting

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

Illustration:

Input String : Lazyroar
Output String : eeeefGGkkorss

Procedure: 

  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 the Character array to String.

Example 2

Java




// Java Program to Sort a Mixed String Containing
// Uppercase and Lowercase Characters
 
// Importing required classes
import java.util.Arrays;
import java.util.Comparator;
 
// Main class
class GFG {
    // Method 1
    // To sort a mixed string
    public static String sortString(String inputString)
    {
        // Converting 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>() {
             
          // Method 2
            // To compare characters
            @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();
    }
 
    // Method 3
    // MAin driver method
    public static void main(String[] args)
    {
        // Custom input string
        String inputString = "Lazyroar";
 
        // Calling method 1 to sort input string
        // and storing in a string
        String outputString = sortString(inputString);
 
        // Print and display the input and output strings
        System.out.println("Input String : " + inputString);
        System.out.println("Output String : "
                           + outputString);
    }
}


Output

Input String : Lazyroar
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 Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

RELATED ARTICLES

Most Popular

Recent Comments