假设我有两个字符串,
String s1 = "AbBaCca";
String s2 = "bac";
我想执行一个检查,返回s2包含在s1中。我可以这样做:
return s1.contains(s2);
我非常确定contains()是区分大小写的,但是我不能从阅读文档中确定这一点。如果是的话,我想我最好的方法是:
return s1.toLowerCase().contains(s2.toLowerCase());
撇开所有这些不谈,有没有另一种(可能更好的)方法可以在不考虑大小写敏感性的情况下完成这个任务?
我做了一个测试,找到一个字符串的大小写不敏感匹配。我有一个150000个对象的向量,所有对象都有一个字符串作为一个字段,并想找到匹配字符串的子集。我尝试了三种方法:
Convert all to lower case
for (SongInformation song: songs) {
if (song.artist.toLowerCase().indexOf(pattern.toLowercase() > -1) {
...
}
}
Use the String matches() method
for (SongInformation song: songs) {
if (song.artist.matches("(?i).*" + pattern + ".*")) {
...
}
}
Use regular expressions
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("");
for (SongInformation song: songs) {
m.reset(song.artist);
if (m.find()) {
...
}
}
定时结果为:
没有尝试匹配:20毫秒
低匹配:182毫秒
字符串匹配:278毫秒
正则表达式:65毫秒
对于这个用例,正则表达式看起来是最快的。