Let’s learn sort characters alphabetically in a string in java.
Sort characters alphabetically in a string in java
To sort string characters alphabetically we do not have any method in String class. So we are using different methods in sorting characters alphabetically in a string.
So here the first method we are applying is toCharArray() method. This method converts given string to a new character array.
Another method is sort() method of Arrays class. This method sorts the given character array in ascending order.
Before final step we have to create new String to store alphabetically sorted string characters. Because we know String is immutable in java.
Finally use String class constructor to create sorted string that contains the characters of the character array.
Here’s the example on sort characters alphabetically in a string.
import java.util.Arrays; public class CharactersAlphabetically { public static void main(String[] args) { String strInput = "flowerbrackets"; // converting string to char array char[] ch = strInput.toCharArray(); // sorting char array Arrays.sort(ch); // converting char array to string String strSorted = String.valueOf(ch); System.out.println("sort string characters alphabetically: " + strSorted); } }
Output:
sort string characters alphabetically: abceefklorrstw
Also read – polymorphism in java