Check whether a string is a substring of another

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. #programming #blog #interview #cpp #placement

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door