Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use `string.startsWith()` method ignoring the case?

Tags:

java

string

People also ask

How do you make a string ignore case?

Java String equalsIgnoreCase() Method The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

Does startsWith ignore case Java?

The accepted answer is wrong. If you look at the implementation of String. equalsIgnoreCase() you will discover that you need to compare both lowercase and uppercase versions of the Strings before you can conclusively return false .

Is startsWith () case sensitive?

startsWith method is case sensitive.

How do you ignore a character case in Java?

Ignore Case Using equalsIgnoreCase() Method in Java This method returns true if two strings are equal after ignoring their cases. If the length of two strings are the same and the corresponding characters in the two strings are the same, they are regarded as equal, ignoring the case.


Use toUpperCase() or toLowerCase() to standardise your string before testing it.


One option is to convert both of them to either lowercase or uppercase:

"Session".toLowerCase().startsWith("sEsSi".toLowerCase());

This is wrong. See: https://stackoverflow.com/a/15518878/14731


Another option is to use String#regionMatches() method, which takes a boolean argument stating whether to do case-sensitive matching or not. You can use it like this:

String haystack = "Session";
String needle = "sEsSi";
System.out.println(haystack.regionMatches(true, 0, needle, 0, 5));  // true

It checks whether the region of needle from index 0 till length 5 is present in haystack starting from index 0 till length 5 or not. The first argument is true, means it will do case-insensitive matching.


And if only you are a big fan of Regex, you can do something like this:

System.out.println(haystack.matches("(?i)" + Pattern.quote(needle) + ".*"));

(?i) embedded flag is for ignore case matching.


I know I'm late, but what about using StringUtils.startsWithIgnoreCase() from Apache Commons Lang 3 ?

Example :

StringUtils.startsWithIgnoreCase(string, "start");

Just add the following dependency to your pom.xml file (taking the hypothesis that you use Maven) :

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>