0
String s ="Ganesh";

System.out.println(""+s.indexOf("ga"));
System.out.println(""+s.indexOf("Ga"));

When I run this, I get -1 for s.indexOf("ga") and 0 for s.indexOf("Ga")

I want to get 0 for both.

How to achieve this?

Buhake Sindi
  • 82,658
  • 26
  • 157
  • 220
RVG
  • 3,430
  • 4
  • 33
  • 61

4 Answers4

2

Unfortunately, there is no indexOfIgnoreCase() method, but you can achieve the same with using toLowerCase().

System.out.println(""+s.toLowerCase().indexOf("ga"));
Buhake Sindi
  • 82,658
  • 26
  • 157
  • 220
1

To use indexOf case-insensitive you can convert the Strings to lowercase first:

System.out.println("" + s.toLowerCase().indexOf("ga".toLowerCase()));
System.out.println("" + s.toLowerCase().indexOf("Ga".toLowerCase()));
Uwe Plonus
  • 9,235
  • 4
  • 36
  • 47
1

use the toLowerCase() or the toUpperCase() method of the String class, before you use the indexOf().

htz
  • 1,017
  • 1
  • 13
  • 35
1

You can convert the string you're looking for to lower or upper case when using indexOf, this way you'll always get the correct index regardless of casing

String s = "Ganesh";
String s2 = "ga";
String s3 = "Ga";

System.out.println(s.toLowerCase().indexOf(s2.toLowerCase()));
System.out.println(s.toLowerCase().indexOf(s3.toLowerCase()));

> 0
> 0

You can even put it into your own method like this:

public int indexOfIgnoreCase(String s, String find) {
    return s.toLowerCase().indexOf(find.toLowerCase());
}

Then you can use it like this:

String s = "Ganesh";

System.out.println(indexOfIgnoreCase(s, "ga"));
System.out.println(indexOfIgnoreCase(s, "Ga"));

> 0
> 0
JREN
  • 3,357
  • 3
  • 24
  • 43