如何在 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
广告