Java Sort String
In this article, you will be acknowledged about how to sort a string in Java.
Introduction
Firstly, let us revise what is string
Strings are collections of characters that are frequently used in Java programming. Objects in the programming language Java include strings. For creating and manipulating strings, the Java platform offers the String class.
Although there is no method in the string class that explicitly sorts a string, we may nevertheless sort a string by using other techniques one after the other. A series of characters make up the string. String objects in Java are immutable, which simply means they can never be modified after they have been created.
There are two ways to create a string in java
- By String Literal
- By new Keyword
By String Literal
The syntax would be as follows
String s = “ Hello Man”;
By new Keyword
String s = new String(“Hello Man”);
Methods for sorting the string
In Java, there are two methods available for sorting any string.
- Without sort() method
- With sort() method
Without sort() method
Here, we'll lay out a method for sorting a string without of any specified reasoning. So, from the perspective of an interview, it does become a crucial strategy.
Process
- By using toCharArray() method of a String class, convert a string to an array.
- Now check for swapping array elements using nested loops.
- Print the components of this character array.
Now let us write a simple java code that depicts the above procedure
File name: WithoutSort.java
// Java code that uses the toCharArray() function to alphabetically sort a string without //leveraging the sort() method
// importing the necessary classes
import java.io.*;
import java.util.Arrays;
class WithoutSort {
public static void main(String[] args) throws Exception
{
// separate string input
String str = "helloman";
// string to array conversion for computation
char arr[] = str.toCharArray();
// Nested loops enabling character comparison in the previous character array
char temp;
int i = 0;
while (i < arr.length) {
int j = i + 1;
while (j < arr.length) {
if (arr[j] < arr[i]) {
// evaluating each character individually
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j += 1;
}
i += 1;
}
// Now that the loop is finished, the entire array has been iterated.
System.out.println(arr);
}
}
Output
aehllmno
With sort() method
Process
- The key logic is to use the String class' toCharArray() function on the input sequence to turn it into a character array.
- To sort a character array, use the Arrays.sort(char c[]) method.
- Create an arranged string from the char array using the constructor of the String class.
Now let us write a code for the above process
File name: WithSort.java
// Java code that uses the toCharArray() function to alphabetically sort a string The sort() //technique is employed here.
// Arrays class from the java.util package being imported
import java.util.Arrays;
public class WithSort {
// To sort a string alphabetically
public static String sortString(String inputString)
{
// raw string to character array conversion
char tempArray[] = inputString.toCharArray();
// utilizing temp array to sort
Arrays.sort(tempArray);
// providing a new, sorted string
return new String(tempArray);
}
public static void main(String[] args)
{
// individual string entered
String inputString = "helloman";
String outputString = sortString(inputString);
// Printing and displaying instructions
// Enter a string
System.out.println("Input String : " + inputString);
// Resulting string
System.out.println("Output String : "+ outputString);
}
}
Output
aehllmno
There is another procedure that is considered to be improved technique by using the sort() method only
Procedure
- Raw string into character array conversion There isn't a simple way to do it. To populate the array, we'll use a for loop.
- To sort a character array, use the Arrays.sort(T [], Comparator c) method. To achieve this, we must create the compare() methodology based on our unique sorting characteristics.
- The Character array can now be converted to a String using StringBuilder.
The example program would be as follows
File name: WithSort1.java
// Sorting a Mixed String of Capital letters and Lower case letter Characters in Java
// importing the necessary classes
import java.util.Arrays;
import java.util.Comparator;
class WithSort1 {
public static String sortString(String inputString)
{
// converting a string input into a character array
Character tempArray[]
= new Character[inputString.length()];
for (int i = 0; i < inputString.length(); i++) {
tempArray[i] = inputString.charAt(i);
}
// Sort without considering the case
Arrays.sort(tempArray, new Comparator<Character>() {
// comparison of characters
public int compare(Character c1, Character c2)
{
return Character.compare(
Character.toLowerCase(c1),
Character.toLowerCase(c2));
}
});
// To transform a Character array to a String, use StringBuilder.
StringBuilder sb
= new StringBuilder(tempArray.length);
for (Character c : tempArray)
sb.append(c.charValue());
return sb.toString();
}
public static void main(String[] args)
{
// each input string
String inputString = "helloman";
// Sorting the input string and putting it in a string by calling method 1
String outputString = sortString(inputString);
// Input as well as output strings should be printed and displayed.
System.out.println("Input String : " + inputString);
System.out.println("Output String : "
+ outputString);
}
}
Output
aehllmno