Replace part of a string with another string

前端 未结 15 2351
终归单人心
终归单人心 2020-11-22 02:54

Is it possible in C++ to replace part of a string with another string?

Basically, I would like to do this:

QString string(\"hello $name\");
string.re         


        
15条回答
  •  花落未央
    2020-11-22 03:34

    To have the new string returned use this:

    std::string ReplaceString(std::string subject, const std::string& search,
                              const std::string& replace) {
        size_t pos = 0;
        while ((pos = subject.find(search, pos)) != std::string::npos) {
             subject.replace(pos, search.length(), replace);
             pos += replace.length();
        }
        return subject;
    }
    

    If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

    void ReplaceStringInPlace(std::string& subject, const std::string& search,
                              const std::string& replace) {
        size_t pos = 0;
        while ((pos = subject.find(search, pos)) != std::string::npos) {
             subject.replace(pos, search.length(), replace);
             pos += replace.length();
        }
    }
    

    Tests:

    std::string input = "abc abc def";
    std::cout << "Input string: " << input << std::endl;
    
    std::cout << "ReplaceString() return value: " 
              << ReplaceString(input, "bc", "!!") << std::endl;
    std::cout << "ReplaceString() input string not modified: " 
              << input << std::endl;
    
    ReplaceStringInPlace(input, "bc", "??");
    std::cout << "ReplaceStringInPlace() input string modified: " 
              << input << std::endl;
    

    Output:

    Input string: abc abc def
    ReplaceString() return value: a!! a!! def
    ReplaceString() input string not modified: abc abc def
    ReplaceStringInPlace() input string modified: a?? a?? def
    

提交回复
热议问题