有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:为什么是字符串。compareIgnoreCase()使用两个字符。toUpperCase()和字符。toLowerCase()?

String类的compareToIgnoreCase方法是使用下面代码段(jdk1.8.0_45)中的方法实现的

i.为什么Character.toUpperCase(char)Character.toLowerCase(char)都用于比较?它们中的任何一个都不能满足比较的目的吗

二,。为什么不使用s1.toLowerCase().compare(s2.toLowerCase())来实现compareToIgnoreCase我知道同样的逻辑可以用不同的方式实现。但是,我仍然想知道是否有具体的理由选择其中一个

    public int compare(String s1, String s2) {
        int n1 = s1.length();
        int n2 = s2.length();
        int min = Math.min(n1, n2);
        for (int i = 0; i < min; i++) {
            char c1 = s1.charAt(i);
            char c2 = s2.charAt(i);
            if (c1 != c2) {
                c1 = Character.toUpperCase(c1);
                c2 = Character.toUpperCase(c2);
                if (c1 != c2) {
                    c1 = Character.toLowerCase(c1);
                    c2 = Character.toLowerCase(c2);
                    if (c1 != c2) {
                        // No overflow because of numeric promotion
                        return c1 - c2;
                    }
                }
            }
        }
        return n1 - n2;
    }

共 (3) 个答案

  1. # 1 楼答案

    有些语言的特殊字符被转换为大写或小写字符(或字符序列)

    因此,对于这种特殊字符,只使用一个大小写可能会有一些问题

    例如,德语中的字符Eszett ß被转换为大写的SS。维基百科:

    The name eszett comes from the two letters S and Z as they are pronounced in German. Its Unicode encoding is U+00DF.

    因此,如果只使用较低的比较,像groß和gross这样的词就会产生失败


    @chrylis这里是一个有效的例子

        System.out.println("ß".toUpperCase().equals("SS"));  // True
        System.out.println("ß".toLowerCase().equals("ss"));  // false
    

    多亏了@chrylis的评论,我做了一些额外的测试,在String类中发现了一个可能的错误:

        System.out.println("ß".toUpperCase().equals("SS"));  // True
        System.out.println("ß".toLowerCase().equals("ss"));  // false
    
        but
    
        System.out.println("ß".equalsIgnoreCase("SS"));  // False
        System.out.println("ß".equalsIgnoreCase("ss"));  // False
    

    因此,至少有一种情况是,如果手动将两个字符串都转换为大写,则两个字符串相等,但如果忽略大小写进行比较,则两个字符串不相等

  2. # 2 楼答案

    下面是一个使用土耳其语i的例子:

    System.out.println(Character.toUpperCase('i') == Character.toUpperCase('İ'));
    System.out.println(Character.toLowerCase('i') == Character.toLowerCase('İ'));
    

    第一行打印false;第二个trueIdeone demo

  3. # 3 楼答案

    从Character类文档中,在toUpperCase和toLowerCase方法中,它声明:

    Note that Character.isUpperCase(Character.toUpperCase(ch)) does not
    always return true for some ranges of characters, particularly those 
    that are symbols or ideographs. (Similar for toLowerCase)
    

    由于比较中可能存在异常,他们会检查这两种情况,以尽可能给出最准确的响应