How to check if a String contains another String in a case insensitive manner in Java?

前端 未结 19 1436
渐次进展
渐次进展 2020-11-22 03:20

Say I have two strings,

String s1 = \"AbBaCca\";
String s2 = \"bac\";

I want to perform a check returning that s2 is contained

19条回答
  •  情深已故
    2020-11-22 04:20

    If you have to search an ASCII string in another ASCII string, such as a URL, you will find my solution to be better. I've tested icza's method and mine for the speed and here are the results:

    • Case 1 took 2788 ms - regionMatches
    • Case 2 took 1520 ms - my

    The code:

    public static String lowerCaseAscii(String s) {
        if (s == null)
            return null;
    
        int len = s.length();
        char[] buf = new char[len];
        s.getChars(0, len, buf, 0);
        for (int i=0; i= 'A' && buf[i] <= 'Z')
                buf[i] += 0x20;
        }
    
        return new String(buf);
    }
    
    public static boolean containsIgnoreCaseAscii(String str, String searchStr) {
        return StringUtils.contains(lowerCaseAscii(str), lowerCaseAscii(searchStr));
    }
    

提交回复
热议问题