1
你好同事,我有一个关于递归的问题,我不明白,是C++和全新的。因此,对于此练习,我正在完成,我需要:1.向用户询问一个字符串2.要求用户输入一个字符串,以便在输入的第一个字符串中进行搜索。 3.如果发现它,报告和索引字符串。例如,用户输入字符串“搜索我”,搜索的字符串是“我”,索引将返回“7”。我在这一点上投入了一些关于如何完成它的帮助,任何帮助将不胜感激。这是我迄今为止的代码。 for循环中的内容并不完整,仅供参考。递归的索引
int index_of(string stringToSearchIn, string stringToSearchFor, int index)
{
if (stringToSearchIn.length() < stringToSearchFor.length())
{
cout << "Your string cannot be found." << endl;
system("PAUSE");
return OUTLIER;
}
else
{
bool found = true;
for (int i = ZERO; i < stringToSearchFor.length; i++)
{
found = found && stringToSearchIn(i) == stringToSearchFor(i);
}
return index;
}
return index_of(stringToSearchIn.substr(INCREASE), stringToSearchFor, index++);
}
int main()
{
//Initializing values
string userString;
string userSearch;
int userIndex = 0;
//Asking for user input for string
cout << "This program will find the occurence of one string inside of another." << endl;
cout << "Enter the string to be searched: " << userString;
//Getting the string
getline(cin, userString);
//Asking for user input for search input
cout << "Now enter the string you want to search for: " << userSearch;
//Getting the string
getline(cin, userSearch);
//Displaying results
cout << "The index of the substring is = " << index_of(userString, userSearch, userIndex);
//Keeping console window open until key press
system("PAUSE");
return ZERO;
}
为什么你让你的生活困难......当你可以使用“std :: size_t pos = str.find(firstString)” – ravi 2014-11-08 18:42:56
不要试图让生活更难....我没有使用过str.find(firstString)。我仍然可以使用这个函数来维护递归吗? – DEnumber50 2014-11-08 18:45:28
@ DEnumber50 find是类std :: string的成员函数。对于你的任务,我认为你不应该使用它。使用我的函数。:) – 2014-11-08 19:20:25