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 ?

1

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped :) Upvoted & accepted as answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.