对于我的赋值,我必须有两个函数(一个main函数和一个递归辅助函数),目的是在字符串中搜索一个字符串,然后提供字符串起始的索引。例如:
字符串:嗨,我是一匹马
要搜索的字符串:horse
返回:10
我编写了一个程序来执行此操作,但唯一的问题是在我的recursiveHelper函数中我通过
检查下一个索引 return recursiveHelper(s.substr(1), t, ++count);
我的老师告诉我,在调用辅助函数时不应该更改字符串s。有人可以告诉我为什么,并为我提供了一个方法,因为我一直在寻找整个周末无济于事。谢谢!
完整计划:
#include <iostream>
#include <string>
using namespace std;
// recursiveHelper function
// purpose: locate the first instance of the string t within the string s
// Parameters: string, string, int
// Returns: int
int recursiveHelper(string s, string t, int count)
{
// Length variables
int inputOneLength = s.length();
int inputTwoLength = t.length();
// Figure out the base case. Same format as lab10 really
if (inputOneLength < inputTwoLength)
{
return -1;
}
else
{
// Check the first index -- compare the strings character by character
if (s.substr(0, inputTwoLength) == t)
{
return count;
}
else
{
// Check the next index
return recursiveHelper(s.substr(1), t, ++count);
}
}
}//end of recursiveHelper
// index_of function
// purpose: locate the first instance of the string t within the string s
// Parameters: string, string
// Returns: int
int index_of(string s, string t)
{
// Initialize the count
int count = 0;
// Send to the helper
count = recursiveHelper(s, t, count);
return count;
}//end of index_of
int main()
{
// Variables
string inputOne = "";
string inputTwo = "";
// Prompt user input
cout << "This program will find the occurence of one string inside another." << endl;
cout << "\nEnter the string to be searched: ";
getline(cin, inputOne);
cout << "Now enter the string you want to search for: ";
getline(cin, inputTwo);
// Pass to index_of function
int index = index_of(inputOne, inputTwo);
// Output results
if (index != -1)
{
cout << "The index of substring is = " << index << endl;
}
else
{
cout << "Can't find this string." << endl;
}
system("PAUSE");
return 0;
}//end of main
答案 0 :(得分:3)
你的老师错了。
s
永远不会改变!
这里是string::substr()
的定义
string substr (size_t pos = 0, size_t len = npos)
const ;
const 关键字表示该方法不会更改对象。
你总是从调用string::substr()