I have a problem with a recursive function I'm trying to write. The purpose of the function is to find a string within a string and then return the index at which the second string is located inside the first using recursion.
I am able to do this. The problem comes when the second string isn't contained in the first string. I'm want to out to the user that the second string was not found. I can't get it to relay that message.
int index_of(string s, string t){
int len1 = s.length(), len2 = t.length(), index = 0;
if (len1==len2){
if (s.substr(index, len2) == t){
return index;
}else{
return -1;
}
else{
index++;
return index_of(s.substr(index, len1),t)+index;
}
}
int main(){
string strOne = "", strTwo = "";
cout << "This program will find the ocurrence of one string within another.\n\nEnter the string to be searched:\t";
getline(cin, strOne);
cout << "\nNow enter the string you want to search for:\t";
getline(cin, strTwo);
int index = index_of(strOne, strTwo);
if (index == -1){
cout << "\nThe second string cannot be found. Sorry!\n\n";}
else{
cout << "\nThe index of the substring is:\t" << index << "\n\n";
}
system("PAUSE");
return 0;
}
Any help would be greatly appreciated! :)