How to find and replace string?

后端 未结 10 1147
感动是毒
感动是毒 2020-11-27 03:51

If s is a std::string, then is there a function like the following?

s.replace(\"text to replace\", \"new text\");
10条回答
  •  广开言路
    2020-11-27 04:05

    Do we really need a Boost library for seemingly such a simple task?

    To replace all occurences of a substring use this function:

    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
    

提交回复
热议问题