Search code examples
c++stringreplacefindfunction-definition

my (find & replace) method is not working properly


I am actually trying to code a program to perform (find & replace) on a given string but it is not working properly (it partially works specially in the first occurrence).

any idea? here is below the code:

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

Solution

  • This call of the member function replace

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

    is incorrect. The second argument must specify the number of characters to be replaced.

    The function should be defined the following way

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

    Here is a demonstrative program.

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

    The program output is

    Hello C++ strings!