【发布时间】:2021-11-24 11:10:01
【问题描述】:
我实际上正在尝试编写一个程序来对给定的字符串执行(查找和替换),但它不能正常工作(它在第一次出现时部分特别工作)。
有什么想法吗?下面是代码:
string Find_Replace(string str,string substr,string replacement){
int x = substr.length();
int i = 0;
for(i = str.find(substr,0);i!=string::npos;i=str.find(substr,i)){
str.replace(i,i+x,replacement);
i++;
}
return str;
}
int main(){
cout << "Please enter a text:-" << endl;
string str;
string substr;
string replacement;
getline(cin, str);
cout<<"Please enter a word to find:-"<<endl;
getline(cin,substr);
cout<<"Please enter the replacement text:-"<<endl;
getline(cin,replacement);
cout<<"The text after process:-"<<endl;
cout<<Find_Replace(str,substr,replacement);
return 0;
}
【问题讨论】:
-
请问实际输出与预期输出?
-
@ErmiyaEskandary 如果我写了例如“我吃代码,你吃代码”并将“吃”替换为“爱”,那么预期将是“我爱代码,你爱代码”,但实际是“我爱你,你爱”
-
字符串
substr和replacement是否保证长度相同?如果没有,您可能需要在字符串中间插入/删除字符,而本程序不会这样做。
标签: c++ string replace find function-definition