tags:

views:

127

answers:

4

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?

+1  A: 
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?

Jack
Character.toLowerCase() would handle all unicode charaters.
bitc
Am I sure I need it: no. But I may in the future, in which case I want to know an alternative.Your code snippet looks like it is from java2s (http://www.java2s.com/Code/Java/Data-Type/StartsWithIgnoreCase.htm), please cite sources, and this does not handle Unicode.
Jason S
Of course it is taken from a link. I can cite the original link, I can also write 15 different versions of it just to show up I'm able to do it :) But wasting so much time for a quite useless question seemed too much.. then __chars__ on JDK are unicode, so it should handle unicode, read documentation before spending time searching if a simple snippet is taken somewhere.
Jack
The best way to do it is using a regexp anyway..
Jack
+2  A: 

How about this:

string2.equalsIgnoreCase(string1.substring(0, string2.length())
Péter Török
+6  A: 

The regionMatches method has a case sensitive parameter.

BenV
cool, thanks! I just noticed http://www.java2s.com/Code/Java/Data-Type/CaseinsensitivecheckifaStringstartswithaspecifiedprefix.htm which seems to take this approach.
Jason S
+1 this was new to me too.
Péter Török
+2  A: 

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

kozmic