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

前端 未结 19 1758
渐次进展
渐次进展 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:26

    Here's some Unicode-friendly ones you can make if you pull in ICU4j. I guess "ignore case" is questionable for the method names because although primary strength comparisons do ignore case, it's described as the specifics being locale-dependent. But it's hopefully locale-dependent in a way the user would expect.

    public static boolean containsIgnoreCase(String haystack, String needle) {
        return indexOfIgnoreCase(haystack, needle) >= 0;
    }
    
    public static int indexOfIgnoreCase(String haystack, String needle) {
        StringSearch stringSearch = new StringSearch(needle, haystack);
        stringSearch.getCollator().setStrength(Collator.PRIMARY);
        return stringSearch.first();
    }
    

提交回复
热议问题