从replaceIgnoreCase说起
来源:互联网 发布:java ee的jdk 编辑:程序博客网 时间:2024/06/05 15:10
昨天写minidao的替换where and 为where 这里因为没有办法判断用户传入的是大写或者小写的字符,只能忽略大小写
最先想到的做法是toLowerCase()单明显是不可取的,因为除了sql 关键字之外用户还是有自己的关键字,这个肯定是要区分大
小写的,然后想到的,穷举这个方法也明显不靠谱,想,百度了下也没有什么好办法,只有自己写了,但是自己写也必须for,然后判断
大小写,比较麻烦相当于自己写个通用方法,这个还是一个比较重要功能,效率必须要考虑的,只能最用用笨办法,String的API是肯定没有了,又看了各个Util的,在org.apache.commons.lang.StringUtils 发现了indexOfIgnoreCase这个方法虽然和目标还有一点差距不过已经非常接近了,就出现了下面的代码
这个是把| and|给删除了
但是每次都要从0开始索引,就又把代码改成
这个就不会重复浪费性能了.而且StringUtils.indexOfIgnoreCase得性能很不错,比我自己写不知高出几个档次.
这里想要说的
代码,如果是通用方法,能调用API的就调用API,org.apache.commons或者guava这里面的代码,不知道经过了多少人检验以及测试,比我们自己再写一个方法要优秀的多.
百度不一定可以百度到你想要的,自己也要多熟悉下API,多看看常用的工具类,如果不是这个,我自己又要写不知多久
最好说说这个实现类
这里大家可以看到好几个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出问题,我们自己更应该做一些参数的校验
我的开源:点击打开链接
0 0
- 从replaceIgnoreCase说起
- 从Object_oriented 说起
- 从AFX_MANAGE_STATE(AfxGetStaticModuleState())说起
- 从“芙蓉姐姐”现象说起
- 不知从何说起
- 从jira说起
- 从AFX_MANAGE_STATE(GetStaticModuleState())说起
- 从辞职说起
- 从"爱因斯坦圆"说起
- 从PDCA说起
- 从被点到说起......
- 从大乘“六度法”说起
- 从AFX_MANAGE_STATE(AfxGetStaticModuleState())说起
- 从Proxy.newProxyInstance说起
- 从中医经络说起
- 从jira说起
- 从揣摩他人说起
- 从jira说起
- Android 数据存储之SQLite
- static作用(修饰函数、局部变量、全局变量)
- 再探Objective-C.8
- Jenkins加Shell实现最简单的持续部署
- ARM汇编初识
- 从replaceIgnoreCase说起
- 再探Objective-C.9
- handbook-fedora
- 黑马程序员──函数、数组
- Linux中只有以下7种文件类型
- SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
- 芯片间的互连标准: HSIC, UniPro, HSI, C2C, LLI
- 国际会议及期刊星级说明
- python除去html标签