Java 中 equals() 与 equalsIgnoreCase() 的区别


在 Java 中使用 equals() 检查两个字符串是否相等。

在 Java 中使用 equalsIgnoreCase() 检查两个字符串是否相等,而不考虑大小写。

假设以下为我们两个字符串 −

String one = "qwerty";
String two = "Qwerty";

两者相等,但大小写不同。由于该方法忽略大小写,使用 equalsIgnoreCase() 方法将这两个字符串视为相等。

在此,我们检查同样的内容 −

if(one.equalsIgnoreCase(two)) {
    System.out.println("String one is equal to two (ignoring the case) i.e. one==two");
}else{
    System.out.println("String one is not equal to String two (ignoring the case) i.e. one!=two");
}

然而,在 equals() 大小写情况下,它们不会被视为相等 −

if(one.equals(two)) {
    System.out.println("String one is equal to two i.e. one==two");
}else{
    System.out.println("String one is not equal to String two i.e. one!=two");
}

以下是最后一个示例。

示例

 在线演示

public class Demo {
    public static void main(String[] args) {
       String one = "qwerty";
       String two = "Qwerty";
       if(one.equalsIgnoreCase(two)) {
          System.out.println("String one is equal to two (ignoring the case) i.e. one==two");
       }else{
          System.out.println("String one is not equal to String two (ignoring the case) i.e. one!=two");
       }
       if(one.equals(two)) {
          System.out.println("String one is equal to two i.e. one==two");
       }else{
          System.out.println("String one is not equal to String two i.e. one!=two");
       }
    }
}

输出

String one is equal to two (ignoring the case) i.e. one==two
String one is not equal to String two i.e. one!=two

更新于: 2020 年 6 月 26 日

超过 4K 浏览量

开启您的 职业

完成课程即可获得认证

开始
广告
© . All rights reserved.