Say I have two strings,
String s1 = "AbBaCca";
String s2 = "bac";
I want to perform a check returning that s2
is contained within s1
. I can do this with:
return s1.contains(s2);
I am pretty sure that contains()
is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:
return s1.toLowerCase().contains(s2.toLowerCase());
All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?
I did a test finding a case-insensitive match of a string. I have a Vector of 150,000 objects all with a String as one field and wanted to find the subset which matched a string. I tried three methods:
Convert all to lower case
Use the String matches() method
Use regular expressions
Timing results are:
No attempted match: 20 msecs
To lower match: 182 msecs
String matches: 278 msecs
Regular expression: 65 msecs
The regular expression looks to be the fastest for this use case.
One problem with the answer by Dave L. is when s2 contains regex markup such as
\d
, etc.You want to call Pattern.quote() on s2:
You can use
The Apache Commons library is very useful for this sort of thing. And this particular one may be better than regular expressions as regex is always expensive in terms of performance.
Basically, it is a method that takes two strings. It is supposed to be a not-case sensitive version of contains(). When using the contains method, you want to see if one string is contained in the other.
This method takes the string that is "sub" and checks if it is equal to the substrings of the container string that are equal in length to the "sub". If you look at the
for
loop, you will see that it iterates in substrings (that are the length of the "sub") over the container string.Each iteration checks to see if the substring of the container string is
equalsIgnoreCase
to the sub.Here's some Unicode-friendly ones you can make if you pull in ICU4j. I guess "ignore case" is questionable for the method names because although primary strength comparisons do ignore case, it's described as the specifics being locale-dependent. But it's hopefully locale-dependent in a way the user would expect.