views:

419

answers:

5

I have two Strings: str1 and str2. How to check if str2 is contained within str1, ignoring case?

+3  A: 

You 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.

Vincent Ramdhanie
Remember to add Javadoc about the behaviour when passing null objects.
Thorbjørn Ravn Andersen
+11  A: 
str1.toLowerCase().contains(str2.toLowerCase())
splix
This isthe more semantically correct solution.
Stefan Kendall
A: 

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

SOA Nerd
A: 

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.

onaclov2000
This is one of the worst answers of all time.Do you have any idea what kind of overhead is involved in loading a regex engine versus calling a method that compares strings linearly?
Stefan Kendall
The OP doesn't mention anything about speed, it just asks how to find a string, if you're not in a speed critical situation, this can be a solution as well. I suppose it may not "impress" your professor as I mentioned it, poor choice of words, but it is a solution nonetheless.
onaclov2000
A: 

You can try with the Class Scanner from java.util package

harigm