Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: equivalent to C's strnicmp? (both startsWith and ignoreCase)

Tags:

java

string

 String string1 = "abCdefGhijklMnopQrstuvwYz";
 String string2 = "ABC";

I had been using string1.startsWith(string2), which would return false in the above example, but now I need to ignore case sensitivity, and there is not a String.startsWithIgnoreCase().

Besides doing

 string1.toLowerCase.startsWith(string2.toLowerCase());

is there an efficient way to see if string1 starts with string2 in a case-insensitive way?

like image 733
Jason S Avatar asked Apr 08 '10 19:04

Jason S


4 Answers

The regionMatches method has a case sensitive parameter.

like image 175
BenV Avatar answered Nov 08 '22 16:11

BenV


Use StringUtils library.

    StringUtils.startsWithIgnoreCase("abCdefGhijklMnopQrstuvwYz", "ABC"); // true

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#startsWithIgnoreCase%28java.lang.String,%20java.lang.String%29

like image 21
kozmic Avatar answered Nov 08 '22 14:11

kozmic


How about this:

string2.equalsIgnoreCase(string1.substring(0, string2.length())
like image 43
Péter Török Avatar answered Nov 08 '22 16:11

Péter Török


string.toLowerCase().startsWith(string2.toLowerCase())
like image 34
user2308953 Avatar answered Nov 08 '22 14:11

user2308953