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?
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?
Unfortunately, there is no indexOfIgnoreCase()
method, but you can achieve the same with using toLowerCase()
.
System.out.println(""+s.toLowerCase().indexOf("ga"));
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()));
use the toLowerCase()
or the toUpperCase()
method of the String
class, before you use the indexOf()
.
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