equalsignorecase函数,java中equalsignorecase用法
上篇我们回顾了String的equals函数,这篇我们就来谈谈它的姐妹函数equalsIgnoreCase,老规矩我们先看下equalsIgnoreCase的官方文档注释是怎么说的:
Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.
简单理解下就是:将字符串与另一个字符串进行比较,忽略大小写因素。如果两个字符串长度相同,且两个字符串中的相应字符大小写相等,则视为相等忽略大小写。紧接着这句话官方文档又加了一段注释如下:
Two characters c1 and c2 are considered the same ignoring case if at least one of the following is true:
The two characters are the same (as compared by the ==operator)
Applying the method Character.toUpperCase(char) to each character produces the same result
Applying the method Character.toLowerCase(char) to each character produces the same result
意思就是 如果三点里面至少有一个为真,则两个字符c1和c2就会被视为相同的(忽略大小写)。
那我们就来段例子说明下:
public static void main(String[] args) { String s1 = "K"; //跟下面的K其实不是同一个字符 String s2 = "K";//跟s3是同一个字符 String s3 = "K"; System.out.println(s1.equalsIgnoreCase(s2));//输出true System.out.println(s1.equals(s2));//输出false System.out.println(s2.equals(s3));//输出true }
这里我解释下:s1不是我们平常的大写英文字母K,它其实是unicode字符\u212A,也就是开尔文温标标记。s2和s3是大写的英文字母K,。所以在不忽略大小写的情况下s1和s2是相等的。根据上述官方解释,s1和s2必须满足三种条件中的一种,实际测试下来s1和s2是在Character.toLowerCase(char)的情况下是相等的。
System.out.println(Character.toLowerCase('\u212A') == Character.toLowerCase('K')); //打印true
从jdk源码看equalsIgnoreCase函数来分析下它是怎么比较的:
public boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true : (anotherString != null) && (anotherString.value.length == value.length) && regionMatches(true, 0, anotherString, 0, value.length); }
可以看到如果两个字符串在==操作返回true的情况下直接返回true了,反之则会判断参数是否为空且两个字符串的长度是否相等,最后再调用regionMatches函数判断,从函数名推断出它内部会做地区相关的匹配。在regionMatches函数内部我们可以看到它是根据Character.toLowerCase和Character.toUpperCase去比较每一个字符的,这里regionMatches函数不是重点,我就截取关键代码来看下:
if (ignoreCase) { // If characters don't match but case may be ignored, // try converting both characters to uppercase. // If the results match, then the comparison scan should // continue. char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) { continue; } // Unfortunately, conversion to uppercase does not work properly // for the Georgian alphabet, which has strange rules about case // conversion. So we need to make one last check before // exiting. if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { continue; } }
先通过Character.toUpperCase转成大写形式的char判断,如果不等,再通过Character.toLowerCase转为小写形式判断。最后判断的注视写的很清楚: 对于格鲁吉亚字母(Georgian alphabet)转换成大写字母不能正常工作,它有奇怪的大小写转换规则。所以我们需要通过Character.toLowerCase做最后一次检查。
这里顺便提句,在Go语言中字符串的忽略大小写比较函数strings.EqualFold中也存在类似的这种异曲同工的比较。大家有兴趣可以去看看。
好了,本期的Java小知识就分享到这了,感谢阅读!
本文地址:百科问答频道 https://www.neebe.cn/wenda/918335.html,易企推百科一个免费的知识分享平台,本站部分文章来网络分享,本着互联网分享的精神,如有涉及到您的权益,请联系我们删除,谢谢!