top of page

Check whether a string is a substring of another

Writer's picture: Prateek ChauhanPrateek Chauhan

Here we are checking if a string s1 is substring of s2. If yes, return index of first occurrence, else return -1.


Example:

Input : s1 = "programmersdoor", s2 = "door"
Output: 11
String "door" is present as a substring of s2.
 

Implementation using C++ :

#include <bits/stdc++.h> 
using namespace std; 

int is_Substring(string s1, string s2) 
{ 
    int M = s1.length(); 
    int N = s2.length(); 
    for (int i = 0; i <= N - M; i++) { 
        int j;
        
        //CHECKS PATTERN MATCH
        for (j = 0; j < M; j++) 
            if (s2[i + j] != s1[j]) 
                break; 
        if (j == M) 
            return i;
    }
    return -1; 
} 
int main() 
{ 
    string s1; 
    string s2; 
    cin>>s1>>endl;
    cin>>s2>>endl;
    int result = is_Substring(s1, s2); 
    if (result == -1) 
        cout << "Not present"; 
    else
        cout << "Present at index " << res; 
    return 0;
} 
Output:
door
programmersdoor
Present at index 11
 

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Follow Programmers Door for more.

10 views0 comments

Recent Posts

See All

Hozzászólások


bottom of page