使用org.apache.commons.lang.StringUtils方法containsAny误区 看看你们遇到过没有

xiaoxiao2021-02-28  76

StringUtils这个工具类相信大家都不陌生,也都用过,我也经常使用。今天在做字符串比较时发现有个比较好玩的东西,记录下来希望能帮助自己记忆一下。

我今天主要说两个方法containsAny和contains都是进行比较字符串是否存在,API也都给出明确的实例

StringUtils.containsAny(null, *) = false StringUtils.containsAny("", *) = false StringUtils.containsAny(*, null) = false StringUtils.containsAny(*, "") = false StringUtils.containsAny("zzabyycdxx", "za") = true StringUtils.containsAny("zzabyycdxx", "by") = true StringUtils.containsAny("aba","z") = false StringUtils.contains(null, *) = false StringUtils.contains(*, null) = false StringUtils.contains("", "") = true StringUtils.contains("abc", "") = true StringUtils.contains("abc", "a") = true StringUtils.contains("abc", "z") = false 但我今天使用的时候,

第一个字符串:46838420642049,46992816225793,46992824151809,46992830762753,46992837524993

,46992842953217,47171435821057,47171629249793,46838420642049

第二个查找的字符串为46591174299905

使用containsAny大家猜猜会输出什么结果呢?

true没错就是true 握草这是怎么回事命名上面的一串ID不存在下面的查找的ID参数吗!!!!

但是使用contains结果是什么呢?

false 这回心里还是暖暖的,终于算是正确了,可是怎么回事呢?containsany怎么就不行了呢?

看了下源码了然了,大家请看

public static boolean containsAny(String str, String searchChars) { if (searchChars == null) { return false; } return containsAny(str, searchChars.toCharArray()); //这里进行了toCharArray } public static boolean containsAny(String str, char[] searchChars) { //然后挨个循环查找匹配 if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) { return false; } int csLength = str.length(); int searchLength = searchChars.length; int csLast = csLength - 1; int searchLast = searchLength - 1; for (int i = 0; i < csLength; i++) { char ch = str.charAt(i); for (int j = 0; j < searchLength; j++) { if (searchChars[j] == ch) { if (CharUtils.isHighSurrogate(ch)) { if (j == searchLast) { // missing low surrogate, fine, like String.indexOf(String) return true; } if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) { return true; } } else { // ch is in the Basic Multilingual Plane return true; } } } } return false; } 我的天哪,不看源码使用的话多可怕,我们使用数字时,一共0-9正好我查找的串的数字在上面的字符串里能够找到。。。。。。。。

所以就ture ture true 了!!!!!!!!

以后我们使用数字字符串进行匹配时要使用contains方法,也许就根本不是个知识点,我拿出来就当是提示一下自己吧,要多看源码哦 哦哈哈!!!!!!

转载请注明原文地址: https://www.6miu.com/read-29973.html

最新回复(0)