[英]String within a string recursive function error
我要编写的递归函数有问题。 该函数的目的是在字符串中找到一个字符串,然后使用递归返回第二个字符串位于第一个字符串内的索引。
我能够做到这一点。 当第二个字符串不包含在第一个字符串中时,就会出现问题。 我想向用户表明找不到第二个字符串。 我无法中继该消息。
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;
}
任何帮助将不胜感激! :)
如果第一个字符串不包含第二个字符串,则index
将无限递增,使string s
长度为零。 因此,您必须检查第一个字符串是否短于第二个字符串。 如果是这样,则不包含子字符串。
if (len1 < len2){
// first string doesn't contain the second
return -2;
}else if (len1==len2){
...
但是您根本不应该在这里使用递归函数。 也有一个内置的功能find
的string
:检查这个问题: 检查是否字符串包含在C ++字符串
首先,最重要的是,由于您未在index_of
定义index
,因此您发布的代码中有很多问题将无法编译。 当然,仅当两个字符串长度相同时才进行比较。 但是由于要根据未定义的变量index
获取子字符串,因此很难弄清楚您要进行的比较是什么; 如果index
为0
,则获取子字符串是没有意义的;如果index
不为0
,则s.substr( index, len2 ) == t
永远不可能为真(因为只有当s
和s
都进入该分支时, t
具有相同的长度。
您真正要做的就是以简单的英语定义函数应该做什么:
如果s
小于t
,则不可能匹配,因此返回-1。
否则,如果s
的开头等于t
,则返回当前索引。
否则,您将递归s
的子字符串,删除第一个字符(并递增index
)。
当然,您还需要在某处维护index
。 在经典递归中,这将作为附加函数参数。
坦白说,我不会构造所有这些子字符串。 在C ++中,使用迭代器更为惯用。 而且我会将递归函数包装在一个非递归函数中,以便用户不必传递任何其他参数:用户可以调用类似以下内容的方法:
int
indexOf( std::string const& text, std::string const& target )
{
return indexOf( 0, text.begin(), text.end(), target );
}
或者,不通过额外的参数:
int
indexOf( std::string const& text, std::string const& target )
{
std::string::const_iterator results
= search( text.begin(), text.end(), target );
return results == text.end()
? -1
: results - text.begin();
}
(我假设这是家庭作业;通常不会对此类问题使用递归。否则,当然,只需在第二个版本中调用std::search
完成工作。或text.find( target )
,它几乎完全返回您想要的内容。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.