I have a recursive function to find the starting index of a substring within a string. I am learning to use recursion, so the find function is not allowed. I believe I have met most of the conditions. This function is supposed to find the correct index in the string. If it is blank it returns -1.
Here is the real problem. If I enter a string “nothing” and search for “jax” it doesn’t return -1. I don’t understand why. Any help please? Here is the code:
The user would enter string s and t passed into below:
int index_of(string s, string t)
{
int start = 0;
int len2 = t.length();
int index = 0;
if (s == "")
{
return -1;
}
else if (s.substr(1).length() <= t.length())
{
return -1;
}
else if ( s.substr(start, len2) == t)
{
return index;
}
else
{
index ++;
return index + index_of(s.substr(1), t);
}
return -1;
}
There are several problems — some minor ones, and some quite important ones.
You have two variables,
startandindex, to indicate “the current position”, but one would be enough.indexcan only be 0 or 1. Therefore, the way it is currently written, you could easily get rid ofindexandstartaltogether.Important: When, during the final recursion, the end of the string is reached, you return
-1to the previous recursive call. Then, because of the way the recursive calls are done, you add1and return that to the previous call, and so forth. The value finally returned is the-1plus the length of the string. That is why you get strange results.This comparison
does not make much sense.
Taking all of this into account, here is an improved version: