List an Array of Strings in alphabetical order

前端 未结 11 1392
独厮守ぢ
独厮守ぢ 2020-12-28 14:49

I have a program which has the user inputs a list of names. I have a switch case going to a function which I would like to have the names print off in alphabetical order.

11条回答
  •  一生所求
    2020-12-28 15:02

    Arrays.sort(stringArray); This sorts the string array based on the Unicode characters values. All strings that contain uppercase characters at the beginning of the string will be at the top of the sorted list alphabetically followed by all strings with lowercase characters. Hence if the array contains strings beginning with both uppercase characters and lowercase characters, the sorted array would not return a case insensitive order alphabetical list

    String[] strArray = { "Carol", "bob", "Alice" };
    Arrays.sort(strList);
    System.out.println(Arrays.toString(hotel));
    

    Output is : Alice, Carol, bob,

    If you require the Strings to be sorted without regards to case, you'll need a second argument, a Comparator, for Arrays.sort(). Such a comparator has already been written for us and can be accessed as a static on the String class named CASE_INSENSITIVE_ORDER.

    String[] strArray = { "Carol", "bob", "Alice" };
    Arrays.sort(stringArray, String.CASE_INSENSITIVE_ORDER);
    System.out.println(Arrays.toString(strArray ));
    

    Output is : Alice, bob, Carol

提交回复
热议问题