The string class does not have any method to sort strings directly, but we can sort strings by applying other methods in turn.
Method 1(natural sorting) :
There are various ways to sort a string in Java. Here are two different ways:
One way to sort a string in Java is by using the Arrays class. This class provides a method called sort() that can be used to sort arrays of primitives, objects, and strings. Here's an example:
String str = "hello world"; char[] charArray = str.toCharArray(); Arrays.sort(charArray); String sortedStr = new String(charArray); System.out.println(sortedStr);
In this example, we first convert the string into a character array using the toCharArray() method. Then, we sort the character array using the sort() method of the Arrays class. Finally, we convert the sorted character array back into a string using the String constructor, and print the sorted string.
Another way to sort a string in Java is by using the StringBuilder class. This class provides a method called reverse() that can be used to reverse a string. Here's an example:
String str = "hello world"; StringBuilder sb = new StringBuilder(str); sb.reverse(); String sortedStr = sb.toString(); System.out.println(sortedStr);
In this example, we first create a StringBuilder object with the input string. Then, we use the reverse() method to reverse the characters in the string. Finally, we convert the StringBuilder object back into a string using the toString() method, and print the sorted string.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.