如何在 Java 中使用 equals() 和 equalsIgnoreCase()。


equals() 方法

此方法將此字串與指定物件進行比較。如果且僅當引數不為 null 並且是表示與此物件相同的字元序列的字串物件時,結果為 true。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "amrood admin";
     
      // checking for equality
      boolean retval1 = str2.equals(str1);
      boolean retval2 = str2.equals(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}

輸出

str2 is equal to str1 = false
str2 is equal to str3 = true

equalsIgnoreCase() 方法

此方法等於 ignoreCase() 方法,除了兩個字串被認為不區分大小寫相等,條件是它們長度相同且兩個字串中的相應字元不區分大小寫相等。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "AMROOD ADMIN";
     
      // checking for equality with case ignored
      boolean retval1 = str2.equalsIgnoreCase(str1);
      boolean retval2 = str2.equalsIgnoreCase(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}

輸出

str2 is equal to str1 = false
str2 is equal to str3 = true

更新於: 26-2-2020

307 次瀏覽

開啟 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.