how to make indexof case insensitive in java
Asked Answered
V

2

7

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.

Vulture answered 19/9, 2014 at 23:47 Comment(1)
possible duplicate of indexOf Case Sensitive?Fear
B
8

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.

Bacteriophage answered 26/2, 2015 at 10:9 Comment(3)
This will not work for unicode, the lengths of İ and i̇ are different (Turkish i with dot)Bi
Why wouldn't that work ? Java string should know how to handle unicode.Peltier
"İ".length() != "İ".toLowerCase().length() : this isn't going to work properly with non english alphabets.Insulation
L
3

One common solution:

yourString.toLowerCase().indexOf("foo");
Lenee answered 19/9, 2014 at 23:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.