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

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

    String container = " Case SeNsitive ";
    String sub = "sen";
    if (rcontains(container, sub)) {
        System.out.println("no case");
    }
    
    public static Boolean rcontains(String container, String sub) {
    
        Boolean b = false;
        for (int a = 0; a < container.length() - sub.length() + 1; a++) {
            //System.out.println(sub + " to " + container.substring(a, a+sub.length()));
            if (sub.equalsIgnoreCase(container.substring(a, a + sub.length()))) {
                b = true;
            }
        }
        return b;
    }
    

    Basically, it is a method that takes two strings. It is supposed to be a not-case sensitive version of contains(). When using the contains method, you want to see if one string is contained in the other.

    This method takes the string that is "sub" and checks if it is equal to the substrings of the container string that are equal in length to the "sub". If you look at the for loop, you will see that it iterates in substrings (that are the length of the "sub") over the container string.

    Each iteration checks to see if the substring of the container string is equalsIgnoreCase to the sub.

提交回复
热议问题