I have two String
s: str1
and str2
. How to check if str2
is contained within str1
, ignoring case?
views:
419answers:
5You can use the toLowerCase()
method:
public boolean contains( String haystack, String needle ) {
haystack = haystack == null ? "" : haystack;
needle = needle == null ? "" : needle;
// Works, but is not the best.
//return haystack.toLowerCase().indexOf( needle.toLowerCase() ) > -1
return haystack.toLowerCase().contains( needle.toLowerCase() )
}
Then call it using:
if( contains( str1, str2 ) ) {
System.out.println( "Found " + str2 + " within " + str1 + "." );
}
Notice that by creating your own method, you can reuse it. Then, when someone points out that you should use contains
instead of indexOf
, you have only a single line of code to change.
I'd use a combination of the contains method and the toupper method that are part of the String class. An example is below:
String string1 = "AAABBBCCC";
String string2 = "DDDEEEFFF";
String searchForThis = "AABB";
System.out.println("Search1="+string1.toUpperCase().contains(searchForThis.toUpperCase()));
System.out.println("Search2="+string2.toUpperCase().contains(searchForThis.toUpperCase()));
This will return:
Search1=true
Search2=false
Well since this is homework if you really want to impress your Professor, use a regex, just look them up a good book is Mastering Regular Expressions by O'Reilly, but it's heavy towards perl, although many of the concepts can apply to most regular expressions.