Finding a substring recursively

MrPickle5

Have no idea why this problem is so hard for me. Iteratively, this is cake but as soon as the stack unwinds it destroys my entire function.

It finds the needle correctly and gives the function a value of true if it finds it. However, it keeps reverting back to false as soon as the call stack is unwound. Does anyone know how to remedy this or what I'm doing wrong with my code?

Here is what I have so far...

bool mySubStr(char * needle, char * haystack)
{
    int needleLength = strlen(needle);
    int haystackLength = strlen(haystack);
    bool found = false;

    if(needleLength < haystackLength)
    {
        if(strncmp(haystack, needle, needleLength) == 0)
        {
            found = true;
        }
        else
        {
            mySubStr(needle, haystack + 1);
        }
    }

    return found;
}
Mike Dinescu

You need to return the result of the recursive call to mySubStr(..):

bool mySubStr(char * needle, char * haystack)
{
   int needleLength = strlen(needle);
   int haystackLength = strlen(haystack);

   if(needleLength > haystackLength)
       return false;

   if(strncmp(haystack, needle, needleLength) == 0)
   {
       return true;
   }

   return mySubStr(needle, haystack + 1);          
}

In your implementation, you were calling the function recursively but were discarding the result:

  else
  {
     mySubStr(needle, haystack + 1);
  }
}

return found;

So in effect, unless the needle happened to be right at the beginning, your function would always return false.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related