I should write a program in C to check whether a given substring is present in the given string. The code I wrote is below but it doesn’t work. Can anyone tell me where the problem is?
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[30]="the test string";
char sbstr[30]="test";
char strcp[30];
int len = strlen(str);
int i=0;
int p=0;
while(i<len)
{
while (str[i] != '\0' && str[i] != ' ')
{
strcp[i] = str[i];
++i;
}
strcp[i] = '\0';
p = strcmp(sbstr, strcp);
if (p==0)
{
printf("exist");
break;
}
++i;
}
}
>Solution :
For the array strcp
char strcp[30];
you need to support a separate index.
Something like
int j = 0;
while (str[i] != '\0' && str[i] != ' ')
{
strcp[j++] = str[i++];
}
strcp[j] = '\0';
Pay attention to that there is standard C function strstr that can be used to perform the task.