How to know if a given string is substring from another string in Java

后端 未结 16 1771
情歌与酒
情歌与酒 2020-12-20 18:58

Hi I have to compute if a given string is substring of a bigger string. For example

String str = \"Hallo my world\";
String substr = \"my\"
<
16条回答
  •  半阙折子戏
    2020-12-20 19:17

    Go through this method. visit for tricky code

    public static boolean isSubString(String s, String sub) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == sub.charAt(count)) {
                count++;
            } else {
                i-=count;
                count = 0;
            }
            if (count == sub.length()) {
                return true;
            }
    
        }
        return false;
    }
    

提交回复
热议问题