2

Can we use "contains" and "equalignorecase" functions of string at same time.

i had a data in which i need to search a string "NBN", if found i need to update a flag. But im seeing there are

"nBN","nBn","NBn","nbN","NbN","Nbn"

also existing in the set of data . so i'm getting multiple combinations and comparisons.

Is there any way to overcome these many comparisons by using both functions at a time ?

4

5 回答 5

5

您可以使用 Apache StringUtils#containsIgnoreCase()

 StringUtils.containsIgnoreCase("WholeString", "NBn");
于 2013-10-09T04:58:14.190 回答
4

认为您可能会发现它更易于使用String#toLowerCase,而不是String#equalsIgnoreCase

例如...

if ("I want my NBN".toLowerCase().contains("nbn")) {...}
于 2013-10-09T04:59:28.763 回答
2

虽然没有直接的内置功能,但最佳做法是将两个字符串都转换为小写,然后使用 contains()

String matchString = "NPN";
String lowercaseMatchString = matchString.toLowerCase();
String lowercase = stringToTest.toLowerCase();

return lowercaseMatchString.contains(lowercase);
于 2013-10-09T05:00:23.817 回答
0

如果您只想检查您的数据是否包含“NBN”,那么 StringUtils.containsIgnoreCase() 是最好的选择,因为它可以满足确切的目的。但是,如果您还想计算出现次数或其他任何内容,那么编写自定义解决方案将是一个更好的选择。

于 2013-10-09T07:06:45.593 回答
0

来自 Apache Commons
http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html

1337    public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) {
1338        if (str == null || searchStr == null) {
1339            return false;
1340        }
1341        final int len = searchStr.length();
1342        final int max = str.length() - len;
1343        for (int i = 0; i <= max; i++) {
1344            if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) {
1345                return true;
1346            }
1347        }
1348        return false;
1349    }

http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/src-html/org/apache/commons/lang3/CharSequenceUtils.html

187        static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart,
188                CharSequence substring, int start, int length)    {
189            if (cs instanceof String && substring instanceof String) {
190                return ((String) cs).regionMatches(ignoreCase, thisStart, ((String) substring), start, length);
191            } else {
192                // TODO: Implement rather than convert to String
193                return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length);
194            }
195        }
于 2013-10-09T05:09:41.797 回答