Search code examples
c++stringc++11replacestdstring

Replace a character/sequence of characters in a C++ std::string with another sequence of characters


I want to replace all occurrences of & in my std::string with &. Here, is the code snippet codelink

#include <algorithm>
#include <string>
#include <iostream>
int main()
{
    std::string st = "hello guys how are you & so good & that &";
    std::replace(st.begin(), st.end(), "&", "&amp;");
    std::cout << "str is" << st;
    return 1;
}

It shows error that std::replace can't replace string, but it only works with characters. I know i can still have a logic to get my work done, but is there any clean C++ way of doing this ? Is there any inbuilt function ?


Solution

  • A regex replace could make this easier:

    #include <algorithm>
    #include <string>
    #include <iostream>
    #include <regex>
    
    int main()
    {
        std::string st = "hello guys how are you & so good & that &";
        st = std::regex_replace(st, std::regex("\\&"), "&amp;");
        std::cout << "str is" << st;
        return 1;
    }