如果没有数组java,如何排序字符串而不管大小写

时间:2014-10-06 20:16:24

标签: java string sorting

我应该编写一个程序,按升序对字符串进行排序,并考虑将大写字母考虑在内。这是我的代码:

public class CSCD210Lab5
{
   public static void main(String [] args)
   {
      String str1, str2, str3, smallestStr, middleStr, largestStr;

      Scanner kb = new Scanner(System.in);

      System.out.print("Enter your first string: ");
      str1=kb.next();
      System.out.print("Enter your second string: ");
      str2=kb.next();
      System.out.print("Enter your third string: ");
      str3=kb.next();

      smallestStr = str1;
      if (str2.charAt(0) < smallestStr.charAt(0))
         smallestStr = str2;
      if (str3.charAt(0) < smallestStr.charAt(0))
         smallestStr = str3;

      middleStr = str1;
      if ((str1.charAt(0) <= str2.charAt(0) && str2.charAt(0) <= str3.charAt(0)) ||     (str3.charAt(0) <= str2.charAt(0) && str2.charAt(0) <= str1.charAt(0)))
         middleStr = str2;
      if ((str2.charAt(0) <= str3.charAt(0) && str3.charAt(0) <= str1.charAt(0)) || (str1.charAt(0) <= str3.charAt(0) && str3.charAt(0) <= str2.charAt(0)))
         middleStr = str3;

      largestStr = str1;
      if (str2.charAt(0) > largestStr.charAt(0))
         largestStr = str2;
      if (str3.charAt(0) > largestStr.charAt(0))
         largestStr = str3;
      System.out.print("The Strings in Ascending Order Are: " + smallestStr + ", " + middleStr + ", " + largestStr);
    }
}

但是,如果我输入adam,Max和bob作为提示,它会将它们排序为&#34; Max,adam,bob。&#34;如何让它忽略大写?我不应该使用数组。

2 个答案:

答案 0 :(得分:2)

实施使用Comparator<String>进行比较的toLowerCase()

public class SortIgnoreCase implements Comparator<String> {
    @Override
    public int compare(String s1, String s2) {
        return s1.toLowerCase().compareTo(s2.toLowerCase());
    }
}

// ...
List<String> strings = new ArrayList<>();
strings.add(str1);
strings.add(str2);
strings.add(str3);
Collections.sort(strings, new SortIgnoreCase());

答案 1 :(得分:0)

使用比较器。

public class StrIgnoreCaseComparator implements Comparator { public int compareTo(String val1, String val2) { return val1.toLowerCase().compareTo(va2.toLowerCase()); } }