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.