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

后端 未结 16 1772
情歌与酒
情歌与酒 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:39

    *In their any sub string will be count by the form of 1th place of string of substring *

    int isSubstring(string s1, string s2) {
        int M = s1.length();
        int N = s2.length();
    
        for (int i = 0; i <= N - M; i++) {
            int j;
            for (j = 0; j < M; j++)
                if (s2[i + j] != s1[j])
                    break;
    
            if (j == M)
                return i;
        }
    
        return -1;
    }
    
    
    int main() {
        string s1 = "kumar";
        string s2 = "abhimanyukumarroy";
        int res = isSubstring(s1, s2);
        if (res == -1)
            cout << "Not present";
        else
            cout << "Present at index " << res;
        return 0;
    }
    

提交回复
热议问题