用另一个字符序列替换C ++ std :: string中的字符/字符序列

cod*_*ver 1 c++ string replace stdstring c++11

我想,以取代所有出现&在我std::string&。这是代码段代码 链接

#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;
}
Run Code Online (Sandbox Code Playgroud)

它显示了std :: replace无法替换字符串的错误,但仅适用于字符。 我知道我仍然有逻辑可以完成我的工作,但是有什么干净的C ++方式可以做到这一点吗?有内置功能吗?

wal*_*lly 5

一个正则表达式替换可以简化这个过程:

#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;
}
Run Code Online (Sandbox Code Playgroud)