Here you will get a C and C++ program to discover substring in a string.
Example coordinating alludes to discover the position where a string design shows up in a given string. On the off chance that the necessary string is absent in given content, at that point it restores the worth zero.
In the event that the necessary string is available in a given string, it restores the situation of the event of required string or substring.
C Program-
#include<stdio.h>
int main()
{
int i,j,temp;
char str[100]={"This is a pattern matching"};
char substr[20]={"pattern"};
for(i=0;str[i]!='\0';i++)
{
j=0;
if(str[i]==substr[j])
{
temp=i+1;
while(str[i]==substr[j])
{
i++;
j++;
}
if(substr[j]=='\0')
{
printf("The substring is present in given string at position %d\n",temp);
exit(0);
}
else
{
i=temp;
temp=0;
}
}
}
if(temp==0)
printf("The substring is not present in given string\n");
return 0;
}
C++ Program-
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int i,j,temp;
char str[100]={"This is a pattern matching"};
char substr[20]={"pattern"};
for(i=0;str[i]!='\0';i++)
{
j=0;
if(str[i]==substr[j])
{
temp=i+1;
while(str[i]==substr[j])
{
i++;
j++;
}
if(substr[j]=='\0')
{
cout<<"The substring is present in given string at position "<<temp<<"\n";
exit(0);
}
else
{
i=temp;
temp=0;
}
}
}
if(temp==0)
cout<<"The substring is not present in given string\n";
return 0;
}
Output-