我在使用C 的函数返回修改后的字符串中时会得到分割故障。我不知道代码中有什么问题。目的是递归从字符串" S1"中删除字符串。作为参考,我将我的代码包括在帖子中。
#include <iostream>
#include <string>
using namespace std;
string recursiveRemove(string s, string rem);
int main()
{
string s1 = "eat tdydyfygyhdy";
string rem1 = "dy";
//recursively remove the rem string from s
s1 = recursiveRemove(s1, rem1);
cout<<s1<<endl;
return 0;
}
string recursiveRemove(string s, string rem){
cout<<"In recursive function s is now = "<<s<<endl;
cout<<"rem = "<<rem<<endl;
if(s.length() == 0 ){
//cout<<s<<endl;
//return;
return s;
}
if(s == rem){
//cout<<""<<endl;
//return;
return "";
}
if(s.length() < rem.length()){
//cout<<s<<endl;
//return;
return s;
}
else{
cout<<"Entered into Else section"<<endl;
int i = 0, j = 0;
int startInd;
while(i<s.length() && s[i] != rem[j]) {
i++;
}
cout<<"i = "<<i<<endl;
if(i == s.length()){//reached the end of the string
cout<<"i = "<<i<<" s.length() = "<<s.length()<<", s="<<s<<endl;
//cout<<s<<endl;
//return;
return s;//temp;
}
else{//match found for first character
startInd = i;
while(i<s.length() && j<rem.length()){
cout<<"Inside while, s[i] = "<<s[i]<<", rem[j] = "<<rem[j]<<endl;
if(s[i] != rem[j]){
//cout<<"inside if s[i]="<<s[i]<<", rem[j]="
//cout<<s<<endl;
//return;
return s;
}
i++;
j++;
cout<<"after increase i= "<<i<<" j="<<j<<endl;
}
int noOfCharsMatched = i - startInd;
s.erase(startInd, noOfCharsMatched);
s = recursiveRemove(s, rem);
}
}
}
错误似乎在此行: s = recursiveRemove(s, rem);
。
首先,除非使用ampersand(&amp;),否则C 中的参数是按值传递的。这意味着每个s
都是一个副本,将其更改为会影响提供给函数调用的原始参数。
第二,您的功能具有无法返回的执行路径,最终已采用。这是未定义的行为。
您可能意味着要做的是返回递归功能调用的结果。尝试将其更改为return recursiveRemove(s, rem);
。