Write a function substr() that will scan a string for the occurrence of a give substring. the prototype of the function would be:
char *substr(char *string1,char string2);
The function should return a pointer to the element in string1 where strig2 begins. If string2 doesn’t occur in string1 then substr() should return a NULL.
For example, if string1 is “Ena Meena Deeka”, and string2 is “Meena” the substr() should return address of ‘M’ in string1.
Write main() function also that uses the function substr().
#include <iostream.h>
#include<stdio.h>
char *get_substr(char *sub, char *str);
int main()
{
char *substr,*str;
cout<<“Enter the string :”;
gets(str);
cout<<“\nEnter the substring :”;
gets(substr);
substr = get_substr(substr,str);
if (substr!=’\0′)
cout << “substring found: ” <<substr;
else
cout<< “substring not found”;
return 0;
}
char *get_substr(char *sub, char *str) // Return pointer to substring or
null if not found.
{
int t;
char *p, *p2, *start;
for(t=0; str[t]!=’\0′; t++)
{
p = &str[t];
start = p;
p2 = sub;
while(*p2!=’\0′ && *p2==*p) // check for substring
{
p++;
p2++;
}
/* If at end of p2 (i.e., substring), then a match has been found. */ if(!*p2)
return start; // return pointer to beginning of substring
}
return 0;
}