Sort a single String in Java

Sort a single String in Java

If you want to sort the characters of a single String in Java, you can convert the String to a character array, sort the array, and then create a new String from the sorted character array. Here's a simple example:

public class StringSortExample { public static void main(String[] args) { String inputString = "programming"; // Convert the String to a character array char[] charArray = inputString.toCharArray(); // Sort the character array Arrays.sort(charArray); // Create a new String from the sorted character array String sortedString = new String(charArray); System.out.println("Original String: " + inputString); System.out.println("Sorted String: " + sortedString); } } 

In this example:

  1. We start with the inputString variable containing the string "programming."

  2. We use the toCharArray method to convert the input string into a character array called charArray.

  3. We sort the character array using the Arrays.sort method, which rearranges the characters in alphabetical order.

  4. Finally, we create a new string called sortedString from the sorted character array.

When you run the program, it will output:

Original String: programming Sorted String: aggimmnoprr 

As you can see, the characters in the sortedString are in ascending alphabetical order.


More Tags

ubuntu-16.04 tracking syswow64 apache-spark-sql integer-division activity-indicator vertical-scrolling formula ionicons viewgroup

More Java Questions

More Other animals Calculators

More Biochemistry Calculators

More Bio laboratory Calculators

More Various Measurements Units Calculators