Hi Priyanka,
One simple approach to sort a string is to convert the string into a character array, use Arrays.sort() to sort the characters, and then convert it back into a string. Here’s how you can do it:
import java.util.Arrays;
public class SortString {
public static void main(String[] args) {
String s = "edcba";
char[] charArray = s.toCharArray(); // Convert string to character array
Arrays.sort(charArray); // Sort the character array
String sortedString = new String(charArray); // Convert back to string
System.out.println(sortedString); // Output: abcde
}
}
Explanation:
- toCharArray() converts the string to a character array.
- Arrays.sort() sorts the array alphabetically.
- Then, you can easily convert the sorted character array back into a string.
- This is one of the most straightforward ways to java sort string alphabetically.