Search code examples
javaalgorithmsortingcase-insensitive

How do I make string sorting program case insensitive?


I am making a program that will sort a String alphabetically and I want to make it case insensitive. So If I input "aBc" I want it to output "aBc" and not "Bac". We are not using the Array.sort method instead we are learning about the different algorithms. For this project, it specifically said that we should use the selection sort algorithm. The Kbd class is something we use in my Java class, and it's basically like scanner but made shorter into one line.

public class Sträng_uppgift{
public static void main(String[] args){

    String unsorted_string = Kbd.readString("Write a word!, I will sort it alphabetically!");

    char[] chArr = unsorted_string.toCharArray();

    char temp;

    for(int i = 0; i < chArr.length; i++){
        for(int j = i+1; j < chArr.length; j++){
            if(chArr[i] > chArr[j]){
                temp=chArr[i];
                chArr[i] = chArr[j];
                chArr[j] = temp;
            }
        }
        System.out.print(chArr[i]);
    }

}

}


Solution

  • Make your comparison case insensitive. Convert this

    if(chArr[i] > chArr[j]){
    

    to use the same case on both sides. For example,

    if (Character.toUpperCase(chArr[i]) > Character.toUpperCase(chArr[j])) {
    

    or

    if (Character.toLowerCase(chArr[i]) > Character.toLowerCase(chArr[j])) {