Java - String equalsIgnoreCase() 方法



描述

java.lang.String.equalsIgnoreCase() 方法比較此字串與另一個字串,忽略大小寫。如果兩個字串長度相同,並且兩個字串中對應的字元在忽略大小寫的情況下相等,則認為這兩個字串相等(忽略大小寫)。

宣告

以下是 java.lang.String.equalsIgnoreCase() 方法的宣告

public boolean equalsIgnoreCase(String anotherString)

引數

anotherString − 這是要與此字串進行比較的字串。

返回值

如果引數不為空,並且它表示一個忽略大小寫的等效字串,則此方法返回 true,否則返回 false。

異常

以不區分大小寫的方式比較字串示例

以下示例顯示了 java.lang.String.equalsIgnoreCase() 方法的使用。在以下程式中,我們使用值 "sachin tendulkar""amrood admin""AMROOD ADMIN" 例項化 String 類。使用 equalsIgnoreCase() 方法,我們嘗試確定給定的字串在不區分大小寫的情況下是否相等。

package com.tutorialspoint;

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

使用相同字串字面量檢查字串物件示例

如果給定的字串值與指定的物件值相同,則 equalsIgnoreCase() 方法返回 true

在以下程式中,我們使用值 "Java" 例項化 String 類。使用 equals() 方法,我們嘗試確定給定的字串是否等於指定的 "Java" 物件。

package com.tutorialspoint;

public class Equal {
   public static void main(String[] args) {
      
      //instantiate a String class
      String str = new String("Java");
      
      //initialize the string object
      String obj = "java";
      System.out.println("The given string is: " + str);
      System.out.println("The object is: " + obj);
      
      //using the equalsIgnoreCase() method
      System.out.println("The given string is equal to the specified object or not? " + str.equalsIgnoreCase(obj));
   }
}

輸出

執行以上程式後,將產生以下結果:

The given string is: Java
The object is: java
The given string is equal to the specified object or not? true

使用不同字串字面量檢查字串物件示例

如果給定的字串值與指定的

在以下示例中,我們建立一個值為 "HelloWorld" 的字串字面量。使用 equalsIgnoreCase() 方法,我們嘗試確定給定的字串是否等於指定的 "Hello" 物件。

package com.tutorialspoint;

public class Equal {
   public static void main(String[] args) {
      
      //create a String literal
      String str = "HelloWorld";
      
      //initialize the string object
      String obj = "Hello";
      System.out.println("The given string is: " + str);
      System.out.println("The object is: " + obj);
      
      //using the equalsIgnoreCase() method
      System.out.println("The given string is equal to the specified object or not? " + str.equalsIgnoreCase(obj));
   }
}

輸出

以下是以上程式的輸出:

The given string is: HelloWorld
The object is: Hello
The given string is equal to the specified object or not? false
java_lang_string.htm
廣告