A string can be sorted by arranging its characters in a specific order, such as alphabetical or natural order. Java's String class does not provide a direct sort() method because strings are immutable. Therefore, we first convert the string into a character array, sort the characters, and then create a new string from the sorted array.
Example
Input: geeksforgeeks
Output: eeeefggkkorss
Methods to Sort a String
1. Using a Sorting Algorithm
In this approach, we convert the string into a character array and sort the characters using Merge Sort.
Approach
- Convert the string into a character array using toCharArray().
- Divide the character array into smaller parts.
- Recursively sort the smaller parts.
- Merge the sorted parts.
- Convert the sorted character array back into a string.
public class GFG {
// Merge two sorted parts of the array
static void merge(char[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
char[] l = new char[n1];
char[] r = new char[n2];
for (int i = 0; i < n1; i++)
l[i] = arr[left + i];
for (int i = 0; i < n2; i++)
r[i] = arr[mid + 1 + i];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (l[i] <= r[j])
arr[k++] = l[i++];
else
arr[k++] = r[j++];
}
while (i < n1)
arr[k++] = l[i++];
while (j < n2)
arr[k++] = r[j++];
}
// Merge Sort
static void mergeSort(char[] arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
public static void main(String[] args) {
String str = "geeksforgeeks";
char[] chars = str.toCharArray();
mergeSort(chars, 0, chars.length - 1);
String sortedString = new String(chars);
System.out.println("Input String : " + str);
System.out.println("Sorted String : " + sortedString);
}
}
Output
Input String : geeksforgeeks Sorted String : eeeefggkkorss
Explanation
- toCharArray() converts the string into a character array.
- mergeSort() recursively divides the array into smaller parts.
- merge() combines the parts in sorted order.
- new String(chars) creates a new string from the sorted characters.
- The original string remains unchanged because
Stringis immutable.
2. Using Arrays.sort()
Java provides the Arrays.sort() method to sort a character array directly.
Approach
- Convert the string into a character array using toCharArray().
- Use Arrays.sort() to sort the character array.
- Convert the sorted array back into a string.
import java.util.Arrays;
public class GFG {
static String sortString(String str) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
public static void main(String[] args) {
String str = "geeksforgeeks";
System.out.println("Input String : " + str);
System.out.println("Sorted String : " + sortString(str));
}
}
Output
Input String : geeksforgeeks Sorted String : eeeefggkkorss
Explanation
- toCharArray() converts the string into a char[].
- Arrays.sort() sorts the characters according to their natural ordering.
- new String(chars) creates a new sorted string.
- Arrays.sort() is simpler and preferred when a custom sorting algorithm is not required.
3. Custom Sorting Using Comparator
When the string contains uppercase and lowercase characters, we can define a custom ordering.
Approach
- Convert the string into a Character[] array.
- Use Arrays.sort() with a custom Comparator.
- Compare characters using Character.toLowerCase().
- Build the sorted string using StringBuilder.
import java.util.Arrays;
import java.util.Comparator;
public class GFG {
static String sortString(String str) {
Character[] chars = new Character[str.length()];
for (int i = 0; i < str.length(); i++) {
chars[i] = str.charAt(i);
}
Arrays.sort(chars, new Comparator<Character>() {
@Override
public int compare(Character c1, Character c2) {
return Character.compare(
Character.toLowerCase(c1),
Character.toLowerCase(c2)
);
}
});
StringBuilder result = new StringBuilder();
for (Character ch : chars) {
result.append(ch);
}
return result.toString();
}
public static void main(String[] args) {
String str = "GeeksforGeeks";
System.out.println("Input String : " + str);
System.out.println("Sorted String : " + sortString(str));
}
}
Try It Yourself
Output
Input String : GeeksforGeeks Sorted String : eeeefGGkkorss
Explanation
- A Character[] array is used because Comparator works with objects.
- Each character of the string is stored in the array.
- Arrays.sort() sorts the array using the provided comparator.
- Character.toLowerCase() makes the comparison case-insensitive.
- StringBuilder is used to construct the final sorted string.