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 s = “GeeksforGeeks”;
String s = new String (“GeeksforGeeks”);
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
- Without using the sort() method
- By using the sort() method
Illustration:
Input string : "geeksforgeeks"
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:
- Convert string to an array with the help of the toCharArray() method of the String class
- Now use nested loops to check for swapping elements of an array.
- Print these character array elements.
Example
Java
import java.io.*;
import java.util.Arrays;
class GFG {
public static void main(String[] args) throws Exception
{
String str = "geeksforgeeks" ;
char arr[] = str.toCharArray();
char temp;
int i = 0 ;
while (i < arr.length) {
int j = i + 1 ;
while (j < arr.length) {
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j += 1 ;
}
i += 1 ;
}
System.out.println(arr);
}
}
|
Output:
eeeefggkkorss
Method 2: By using the sort() method
2A By using the sort() method- natural sorting
Procedure:
- The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string.
- Now use Arrays.sort(char c[]) method to sort character array.
- Use the String class constructor to create a sorted string from a char array.
Example 1
Java
import java.util.Arrays;
public class GFG {
public static String sortString(String inputString)
{
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
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);
}
}
|
Output
Input String : geeksforgeeks
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 : GeeksforGeeks
Output String : eeeefGGkkorss
Procedure:
- Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.
- 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.
- Now we can use StringBuilder to convert the Character array to String.
Example 2
Java
import java.util.Arrays;
import java.util.Comparator;
class GFG {
public static String sortString(String inputString)
{
Character tempArray[]
= new Character[inputString.length()];
for ( int i = 0 ; i < inputString.length(); i++) {
tempArray[i] = inputString.charAt(i);
}
Arrays.sort(tempArray, new Comparator<Character>() {
@Override
public int compare(Character c1, Character c2)
{
return Character.compare(
Character.toLowerCase(c1),
Character.toLowerCase(c2));
}
});
StringBuilder sb
= new StringBuilder(tempArray.length);
for (Character c : tempArray)
sb.append(c.charValue());
return sb.toString();
}
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);
}
}
|
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
If you like GeeksforGeeks 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 GeeksforGeeks 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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Dec, 2022
Like Article
Save Article