昨天写minidao的替换where and 为where 这里因为没有办法判断用户传入的是大写或者小写的字符,只能忽略大小写
最先想到的做法是
toLowerCase()单明显是不可取的,因为除了sql 关键字之外用户还是有自己的关键字,这个肯定是要区分大
小写的,然后想到的,穷举这个方法也明显不靠谱,想,百度了下也没有什么好办法,只有自己写了,但是自己写也必须for,然后判断
大小写,比较麻烦相当于自己写个通用方法,这个还是一个比较重要功能,效率必须要考虑的,只能最用用笨办法,String的API是肯定没有了,又看了
各个Util的,在org.apache.commons.lang.StringUtils 发现了indexOfIgnoreCase这个方法虽然和目标还有一点差距不过已经非常接近了,就出现了下面的代码
![](https://i-blog.csdnimg.cn/blog_migrate/6dbc23ecd6f97af5065c55dd7928f530.png)
这个是把| and|给删除了
但是每次都要从0开始索引,就又把代码改成
![](https://i-blog.csdnimg.cn/blog_migrate/54ca1f57d9d246e34cdf77b1767fd976.png)
这个就不会重复浪费性能了.而且StringUtils.indexOfIgnoreCase得性能很不错,比我自己写不知高出几个档次.
这里想要说的
代码,如果是通用方法,能调用API的就调用API,org.apache.commons或者guava这里面的代码,不知道经过了多少人检验以及测试,比我们自己再写一个方法要优秀的多.
百度不一定可以百度到你想要的,自己也要多熟悉下API,多看看常用的工具类,如果不是这个,我自己又要写不知多久
最好说说这个实现类
![](https://i-blog.csdnimg.cn/blog_migrate/89e216f002e12cfd448377cc566dd453.png)
这里大家可以看到好几个
IF,可能我们写代码不会这么注意,所以经常会造成异常 ,尽量应该先判断条件,特别是你想写成工具类.
他这里没有做什么,只是for一下字符串,然后调用String的regionMatches 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public
boolean
regionMatches(
boolean
ignoreCase,
int
toffset,
String other,
int
ooffset,
int
len) {
char
ta[] = value;
int
to = offset + toffset;
char
pa[] = other.value;
int
po = other.offset + ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if
((ooffset <
0
) || (toffset <
0
) || (toffset > (
long
)count - len) ||
(ooffset > (
long
)other.count - len)) {
return
false
;
}
while
(len-- >
0
) {
char
c1 = ta[to++];
char
c2 = pa[po++];
if
(c1 == c2) {
continue
;
}
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
;
}
}
return
false
;
}
return
true
;
}
|
最好那个比较感觉是点睛之作,java都怕自己的API出问题,我们自己更应该做一些参数的校验
我的开源:点击打开链接