how to make indexof case insensitive in java

javalearner picture javalearner · Sep 20, 2014 · Viewed 12.5k times · Source

I have a simple question. How do I make indexof case insensitive in java. This question has been already answered in some forum but I didn't understand the answer.

Say for eg.I have a string s = Phone(Conf) I want to pull the record that has (Conf) like this but the users are entering CONF or conf or Conf etc. So my program should be able to pull the record if it finds the word conf in any case.

    if(s.indexOf("(")>-1&& s.indexOf("Conf")>-4 && s.lastIndexOf(")")>-1)
 {
    String s1=s.substring(s.indexOf("(Conf"),s.lastIndexOf(")")+1);
   }

can someone explain me pls? The above code pulls it if the string is (Conf) only.

Answer

Crenguta S picture Crenguta S · Feb 26, 2015

The safest way to do it would be:

content.toLowerCase().indexOf(searchTerm.toLowerCase()), this way you cover 2 possible edge cases when the content may be in lower case and the search term would be in upper case or both would be upper case.