How can I find if a substring is present in a string or not without using find() function? Is there any efficient way to find the substring than using find() function? `
#include <bits/stdc++.h>
using namespace std;
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 = "for";
string s2 = "geeksforgeeks";
int res = isSubstring(s1, s2);
if (res == -1)
cout << "Not present";
else
cout << "Present at index " << res;
return 0;
}
//I found this code on Geeks for geeks but its time complexity is O(M*(N-M)). Can it be reduced?