如何在 Java 中使用 equals() 和 equalsIgnoreCase()。
equals() 方法
该方法比较此字符串与指定对象。当且仅当参数不为 null 且是要表示与该对象相同字符串序列的字符串对象时,结果为真。
示例
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
广告