1

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 ?

wally
  • 10,717
  • 5
  • 39
  • 72
codeLover
  • 3,720
  • 10
  • 65
  • 121

1 Answers1

5

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;
}
wally
  • 10,717
  • 5
  • 39
  • 72