开发者

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

 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.startsWithIgno开发者_JAVA百科reCase().

Besides doing

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

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


The regionMatches method has a case sensitive parameter.


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


How about this:

string2.equalsIgnoreCase(string1.substring(0, string2.length())


string.toLowerCase().startsWith(string2.toLowerCase())


public static boolean startsWithIgnoreCase(String s, String w)
    {
        if (w==null)
            return true;

        if (s==null || s.length()<w.length())
            return false;

        for (int i=0;i<w.length();i++)
        {
            char c1=s.charAt(i);
            char c2=w.charAt(i);
            if (c1!=c2)
            {
                if (c1<=127)
                    c1=Character.toLowerCase(c1);
                if (c2<=127)
                    c2=Character.toLowerCase(c2);
                if (c1!=c2)
                    return false;
            }
        }
        return true;
    }

By the way are you sure you need efficiency here?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜