问题描述
是否可以确定String str1 =ABCDEFGHIJKLMNOP
是否包含字符串模式 strptrn =gHi
?我想知道当字符不区分大小写时是否可能。如果是这样,怎么样?
Is it possible to determine if a String str1="ABCDEFGHIJKLMNOP"
contains a string pattern strptrn="gHi"
? I wanted to know if that's possible when the characters are case insensitive. If so, how?
推荐答案
你可以使用
org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
CharSequence searchStr);
null CharSequence将返回false。
A null CharSequence will return false.
这个优于正则表达式,因为正则表达总是昂贵在性能方面。
This one will be better than regex as regex is always expensive in terms of performance.
对于官方文档,请参阅:
For official doc, refer to : StringUtils.containsIgnoreCase
更新:
如果你是那些
- 的人不想使用Apache commons库
- 不想使用昂贵的
regex / Pattern
解决方案, - 不想使用
toLowerCase
,
- don't want to use Apache commons library
- don't want to go with the expensive
regex/Pattern
based solutions, - don't want to create additional string object by using
toLowerCase
,
你创建额外的字符串对象可以实现自己的自定义 containsIgnoreCase
使用
you can implement your own custom containsIgnoreCase
using java.lang.String.regionMatches
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)
ignoreCase
:如果为true,则在比较字符时忽略大小写。
ignoreCase
: if true, ignores case when comparing characters.
public static boolean containsIgnoreCase(String str, String searchStr) {
if(str == null || searchStr == null) return false;
final int length = searchStr.length();
if (length == 0)
return true;
for (int i = str.length() - length; i >= 0; i--) {
if (str.regionMatches(true, i, searchStr, 0, length))
return true;
}
return false;
}
这篇关于字符串包含 - 忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!