溫馨提示×

equalsignorecase的使用方法有哪些

小億
496
2023-08-01 17:38:06
欄目: 編程語言

在Java中,equalsIgnoreCase()是用于比較兩個字符串是否相等而不考慮大小寫的方法。以下是equalsIgnoreCase()的使用方法:

  1. 直接使用equalsIgnoreCase()方法進行比較:
String str1 = "Hello";
String str2 = "hello";
if (str1.equalsIgnoreCase(str2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are not equal.");
}
  1. 將equalsIgnoreCase()與equals()方法結(jié)合使用:
String str1 = "Hello";
String str2 = "hello";
if (str1.equals(str2) || str1.equalsIgnoreCase(str2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are not equal.");
}
  1. 與toLowerCase()方法結(jié)合使用:
String str1 = "Hello";
String str2 = "hello";
if (str1.toLowerCase().equals(str2.toLowerCase())) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are not equal.");
}

注意:equalsIgnoreCase()方法比較字符串時不考慮大小寫,即使字符串中包含其他字符,只要字母相同就會被認(rèn)為是相等的。

0