Case-insensitive startWith () method

I want to use the startsWith() String method, but ignoring this case.

Suppose I have a String "Session" and I use startsWith on "sEsSi", then it should return true .

+64
java string
03 Oct '13 at 8:16
source share
8 answers

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

+56
03 Oct '13 at 8:19
source share
— -

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

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



Another option is to use the String#regionMatches() method, which takes a boolean argument indicating whether to match case-sensitive or not. You can use it as follows:

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

It checks to see if the needle region from index 0 to length 5 is present in the haystack , starting from index 0 to length 5 or not. The first argument is true , meaning that it will make case insensitive.




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

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

(?i) built-in flag is used to match cases of ignoring.

+63
03 Oct '13 at 8:18
source share
 myString.toLowerCase().startsWith(starting.toLowerCase()); 
+5
Oct 03 '13 at 8:18
source share

try it,

 String session = "Session"; if(session.toLowerCase().startsWith("sEsSi".toLowerCase())) 
+5
Oct 03 '13 at 8:18
source share

You can always do

 "Session".toLowerCase().startsWith("sEsSi".toLowerCase()); 
+2
03 Oct '13 at 8:18
source share

You can use someString.toUpperCase().startsWith(someOtherString.toUpperCase())

+2
Oct 03 '13 at 8:19
source share

starts with and toLowerCase together

like this

 "Session".toLowerCase().startsWith("sEsSi".toLowerCase()); 
+2
Oct 03 '13 at 8:19
source share

You can do something like this: -

 str.toLowerCase().startsWith(searchStr.toLowerCase()); 
+1
Oct 03 '13 at 8:19
source share



All Articles