字符串包含 - 忽略大小写 [英] String contains - ignore case

查看:976
本文介绍了字符串包含 - 忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以确定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);




检查CharSequence是否包含搜索CharSequence而不管
为何,处理null。不区分大小写的定义为
String.equalsIgnoreCase(String)。

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

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.

对于官方文档,请参阅: StringUtils.containsIgnoreCase

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 使用 java.lang.String.regionMatches

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;
}

这篇关于字符串包含 - 忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆