Android String Equality: equals() vs equalsIgnoreCase()
In Android, to determine if two strings are equal, you can use the equals() method or the equalsIgnoreCase() method.
- Utilize the equals() method to compare two strings for equality, taking into account case sensitivity.
String str1 = "hello";
String str2 = "world";
if(str1.equals(str2)){
// 字符串相等
}else{
// 字符串不相等
}
- The equalsIgnoreCase() method is used to compare two strings for equality while ignoring the case.
String str1 = "Hello";
String str2 = "hello";
if(str1.equalsIgnoreCase(str2)){
// 字符串相等
}else{
// 字符串不相等
}
It is important to note that when comparing empty strings or null values, it is best to first check for null to avoid a NullPointerException.
String str1 = "hello";
String str2 = null;
if(str1 != null && str1.equals(str2)){
// 字符串相等
}else{
// 字符串不相等
}