简体   繁体   中英

How do I sort an array ignoring capitalization?

I use sort() to sort my array alphabetically, but it does so from AZ to az. I try to capitalize each word beforehand, but it doesn't work unless it's being printed out, which should be happening after the sorting. At the moment, with this code, it will list the pupils with capital letters, but if it was inputted as lowercase, it will be sorted as lowercase. Putting the capitalize() in the initial for loop, right after assigning the input to the array, doesn't work. Any solutions?

import java.util.Scanner;
import java.util.Arrays;

public class Pupils {
public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    boolean loop = true;
    int names = 0;

    String[] ay = new String[1000];

    for(int i = 0; loop == true; i++) {
            System.out.println("Enter name: ");
            ay[i] = scan.nextLine();
            names++;
            if (ay[i].equals("0")) {
                loop = false;
                ay[i] = " ";
        }
    }

    String[] aay = new String[names - 1];

    for(int i = 0; i < aay.length; i++) {
        aay[i] = ay[i];
    }

    if (names == 1) {
        System.out.print("There are no people in our class.");
    } else if (names == 2) {
        System.out.print("The person in our class is ");
    } else {
        System.out.print("The people in our class are ");
}
    Arrays.sort(aay);
    for(int i = 0; i < names - 1; i++) {
        if(i == names - 2) {
            System.out.print(capitalize(aay[i]) + ".");
        } else if (i == names - 3) {
            System.out.print(capitalize(aay[i]) + " and ");
        } else {
            System.out.print(capitalize(aay[i]) + ", ");
        }
    }

}
public static String capitalize(String line)
{
  return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}

}

What about using Arrays.sort() with a Comparator ? Note that there is a suitable comparator defined in String , so:

Arrays.sort(aay, String.CASE_INSENSITIVE_ORDER);

should do the job.

I suggest storing all the data in the array in lowercase. It will simplify sorting as well as search (if you search for a student in the array, and it was entered as, say "Walter" and you are looking for "walter", you won't find it. If you use lowercase both for storage and for search, it will work).

And since you capitalize the names for printing anyway, the names will still be displayed capitalized.

So instead of doing

        ay[i] = scan.nextLine();

You can do:

        ay[i] = scan.nextLine().toLowerCase();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM