I am pretty close to completing my function. I need to take 2 strings, and return the index of string 2 inside of string 1. I know there is a find function for this, but I am not able to use it. It also has to be done with recursive programming.
I have the following.
int index_of(string haystack, string needle) {
int index = 0;
string test = haystack.substr(index, needle.length());
if (test == needle) {
return index;
}
else {
return 1 + index_of(haystack.substr(1), needle);
}
}
It returns the index of the needle in the haystack no problem but there are 2 things it needs to do I can not figure out.
1) If the needle is not in the haystack, then it needs to return a -1. I have done it so at the end if it does not exist, it returns a -1, but because it is recursive, it then adds the other times it returned 1. I am not sure how to just return a single value at the end without adding all the other instances on it.
2) I am suppose to use a helper function within it and I am not sure how to do that either.
Thanks for any help!
In general, you want to return the value of a recursive function unadulterated. In your case, this:
return 1 + index_of(some_parameters);
Should be this:
return index_of(some_parameters);
Now, you just need to choose parameters such that you can keep track of the index until you need to return it, or alternatively -1.
One such function might have the constructor:
index_of(string haystack, string needle, int index);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments