Implement case insensitive sorting
In Java, the Arrays.sort()
method compares characters using their Unicode values. To sort a string without regards to case-sensitivity, we can modify the sorting algorithm using a Comparator
. In this step, we will edit our previous Java code to sort the string without regards to the case.
import java.util.Arrays;
import java.util.Comparator;
public class SortString {
public static void main(String[] args) {
String originalString = "The quick brown fox jumps over the lazy dog";
String sortedString = "";
Character[] tempArr = toCharacterArray(originalString.toLowerCase()); // convert lowercase string to Character array
Arrays.sort(tempArr, new Comparator<Character>() { // sort with case-insensitive comparator
@Override
public int compare(Character c1, Character c2) {
return c1.compareTo(c2);
}
});
StringBuilder sb = new StringBuilder(tempArr.length); // create a StringBuilder object
for (Character c : tempArr) {
sb.append(c.charValue()); // add sorted characters to the StringBuilder object
}
sortedString = sb.toString(); // convert StringBuilder object to a string
System.out.println("Original String: " + originalString);
System.out.println("Sorted String: " + sortedString);
}
// method to convert a string to Character array
private static Character[] toCharacterArray(String str) {
Character[] arr = new Character[str.length()];
for (int i = 0; i < str.length(); i++) {
arr[i] = str.charAt(i);
}
return arr;
}
}