【发布时间】:2014-11-11 14:54:02
【问题描述】:
我尝试编写的递归函数有问题。该函数的目的是在一个字符串中找到一个字符串,然后使用递归返回第二个字符串在第一个字符串中所在的索引。
我能够做到这一点。当第二个字符串不包含在第一个字符串中时,就会出现问题。我想告诉用户第二个字符串没有找到。我无法让它转发该消息。
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;
}
任何帮助将不胜感激! :)
【问题讨论】:
-
您不应该为此目的使用递归函数。在大字符串上,您会出现堆栈溢出。
-
我不是 C++ 程序员,但你能比较这样的字符串吗:'str1 == str2'?您不必使用 strcmp(str1, str2) 吗?我认为第一个选项只比较字符串的地址?
-
如果
s不包含t,你想让函数做什么?给stdout留言?抛出异常?返回 -1? -
2 个问题。 1)调用者将增加-1。 2)长度比较应该是
>=而不是==