Search code examples
cstringrecursionstrstr

recursive strstr function in c


I wrote my recursive strstr but the problem is that if I have this code:

char *str = "Yesterday all my troubles seemed so far away";
char *subStr[6] = { "Yes", "all", "my", "see", "far", "day" };
char *res;
int i;
printf("%s\n", str);
res = str;
for (i = 0; i<6; i++)
{
    printf("%s\n", subStr[i]);
    res = recursiveStrStr(res, subStr[i]);
    if (res == 0)
    {
        printf("The specified text is not found.\n");
        break;
    }
    else
        printf("The found text: %s\n", res);
}

My strstr return str very well till it gets to i=5 so the substr is "day" and str that left is "far away" and it should return 0 - that means text not found but it returns str dont understand why ?

my strstr code (should be recursive):

int recursiveStrStr(char * str, char *substr)
{

    if (str == NULL  )
        return 0;
    else if (strncmp(str, substr, strlen(substr)) == 0)
        return str;
    else 
        return(recursiveStrStr(str+1, substr));

}

Solution

  • I guess it should be (*str == NULL) ?