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
广告

© . All rights reserved.