In: Computer Science
C programming
Write a function called string in() that takes two string pointers as arguments. If the second string is contained in the first string, have the function return the address at which the contained string begins. For instance, string in(“hats”, “at”) would return the address of the a in hats. Otherwise, have the function return the null pointer. Test the function in a complete program that uses a loop to provide input values for feeding to the function.
#include <stdio.h>
//function to return address if string2 is present in string 1
char* substring(char str1[],char str2[])
{
char *start = NULL;
int count1 = 0, count2 = 0, i, j, flag;
while (str1[count1] != '\0')
count1++;
while (str2[count2] != '\0')
count2++;
for (i = 0; i <= count1 - count2; i++)
{
for (j = i; j < i + count2; j++)
{
flag = 1;
if (str1[j] != str2[j - i])
{
flag = 0;
break;
}
}
if (flag == 1)
{
start = &str1[i];
return start;
}
}
return start; //returns NULL if string is not present else address willl be returned
}
int main() {
char str1[80], str2[50];
for(int i=0;i<5;i++)
{
printf("Enter a string 1: \n");
gets(str1);
printf("Enter string 2:\n");
gets(str2);
char *result = substring(str1,str2);
if(result != NULL)
{
printf("%c \n",result); //print if the first address of character where match occurs
}
else
printf("Not present\n"); //if string 2 is not present
}
}
INPUT AND OUTPUT