Reputation: 45
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 ?
Upvotes: 2
Views: 413
Reputation: 515
If you just want to check the wether your data contains "NBN" then StringUtils.containsIgnoreCase() is the best option as it serves the exact purpose. But if you also want to count the occurrences or anything else then writing a custom solution will be a better option.
Upvotes: 0
Reputation: 1508
From 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 }
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 }
Upvotes: 0
Reputation: 1508
While there is no built in functionality for this directly, best practice is to convert both Strings to lower case then use contains()
String matchString = "NPN";
String lowercaseMatchString = matchString.toLowerCase();
String lowercase = stringToTest.toLowerCase();
return lowercaseMatchString.contains(lowercase);
Upvotes: 2
Reputation: 347234
Think you might find it easier to use String#toLowerCase
instead of String#equalsIgnoreCase
For example...
if ("I want my NBN".toLowerCase().contains("nbn")) {...}
Upvotes: 4
Reputation: 121998
You can use Apache StringUtils#containsIgnoreCase()
StringUtils.containsIgnoreCase("WholeString", "NBn");
Upvotes: 5