I'm a programming student in my first C++ class, and recently we were encouraged to write a simple recursive function to find the first occurrence of a substring in a given string. If found, it returns the index. If the substring is not found, the index_of()
function should return -1. We are encouraged to use a helper function that takes the index as one of its parameters, and this is what I've tried.
For example:
int index_of("Mississippi", "sip"); // this would return a 6
This is supposed to be a simple exercise to help us understand recursion and won't be turned in. My professor stated that our actual assignment with recursion will be much more involved, which is why I really want to understand this simple use of recursion.
I've done this successfully using C-style strings and pointers, but not with C++ std::string objects. What am I doing wrong in my program? My professor stated we should easily be able to write this in 5 mins, but I've been struggling with it for two hours. Here's what I've done so far:
int index_of(string s, string t)
{
int index = 0;
if (s[index] == NULL)
return -1;
else if (starts_with(s, t, ++index))
{
return index;
}
else
return index;
}
bool starts_with(string s, string t, int index)
{
if (t[index] == NULL)
return true;
if ( s[index] == NULL || t[0] != s[index])
return false;
return starts_with(s, t, ++index);
}
As written, this function always returns an index
of 1.