C++ C++;递归搜索函数(学校作业)
对于我的赋值,我必须有两个函数(一个主函数和一个递归辅助函数),目的是在字符串中搜索字符串,然后提供字符串开始的索引。例如: 弦:嗨,我是一匹马 要搜索的字符串:horse 报税表:10 我已经编写了一个程序来实现这一点,但唯一的问题是在我的递归助手函数中,我通过它检查下一个索引C++ C++;递归搜索函数(学校作业),c++,recursion,C++,Recursion,对于我的赋值,我必须有两个函数(一个主函数和一个递归辅助函数),目的是在字符串中搜索字符串,然后提供字符串开始的索引。例如: 弦:嗨,我是一匹马 要搜索的字符串:horse 报税表:10 我已经编写了一个程序来实现这一点,但唯一的问题是在我的递归助手函数中,我通过它检查下一个索引 return recursiveHelper(s.substr(1), t, ++count); 我的老师告诉我,在调用helper函数时,字符串s不应更改。有人能告诉我为什么,并提供给我一个
return recursiveHelper(s.substr(1), t, ++count);
我的老师告诉我,在调用helper函数时,字符串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
#包括
#包括
使用名称空间std;
//递归辅助函数
//目的:在字符串s中找到字符串t的第一个实例
//参数:string,string,int
//返回:int
int recursiveHelper(字符串s、字符串t、int计数)
{
//长度变量
int inputOneLength=s.length();
int inputTwoLength=t.长度();
//找出基本情况。与lab10格式相同
if(输入单位长度<输入单位长度)
{
返回-1;
}
其他的
{
//检查第一个索引——逐个字符比较字符串
如果(s.substr(0,输入长度)=t)
{
返回计数;
}
其他的
{
//检查下一个索引
返回递归助手(s.substr(1),t,++count);
}
}
}//递归助手的结束
//函数索引
//目的:在字符串s中找到字符串t的第一个实例
//参数:string,string
//返回:int
整型索引_of(字符串s,字符串t)
{
//初始化计数
整数计数=0;
//发送给助手
count=递归助手(s、t、count);
返回计数;
}//索引_的末尾
int main()
{
//变数
字符串inputOne=“”;
字符串输入wo=“”;
//提示用户输入
你的老师错了。
s
永远不会更改
以下是string::substr()的定义
string substr(size\t pos=0,size\t len=npos)
const
const关键字表示该方法不会更改对象。
调用string::substr()
语句s.substr(1)时,总是会得到一个新字符串将字符串s减少一个字符?否。它将创建一个新字符串,该字符串由s
的倒数第二个字符组合而成。正如我所说的,const表示对象没有更改。这是由语言定义的,由编译器强制执行。