我的(查找和替换)方法无法正常工作

my (find & replace) method is not working properly

我实际上正在尝试编写一个程序来对给定的字符串执行(查找和替换)但它无法正常工作(它在第一次出现时部分地工作)。

有什么想法吗?下面是代码:

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;
}

本次调用成员函数replace

str.replace(i,i+x,replacement);

不正确。第二个参数必须指定要替换的字符数。

函数应该按如下方式定义

std::string & Find_Replace( std::string &str, const std::string &substr, const std::string &replacement )
{
    auto n1 = substr.length();
    auto n2 = replacement.size();

    for( auto pos = str.find( substr, 0 );
         pos != std::string::npos; 
         pos = str.find(substr, pos ) )
    {
        str.replace( pos, n1, replacement );
        pos += n2;
    }

    return str;
}

这是一个演示程序。

#include <iostream>
#include <string>

std::string & Find_Replace( std::string &str, const std::string &substr, const std::string &replacement )
{
    auto n1 = substr.length();
    auto n2 = replacement.size();

    for( auto pos = str.find( substr, 0 );
         pos != std::string::npos; 
         pos = str.find(substr, pos ) )
    {
        str.replace( pos, n1, replacement );
        pos += n2;
    }

    return str;
}

int main() 
{
    std::string s( "Hello World!" );
    
    std::cout << Find_Replace( s, "World", "C++ strings" ) << '\n';
    
    return 0;
}

程序输出为

Hello C++ strings!