【问题标题】:Replace a character/sequence of characters in a C++ std::string with another sequence of characters [duplicate]用另一个字符序列替换 C++ std::string 中的字符/字符序列[重复]
【发布时间】:2018-04-03 06:32:44
【问题描述】:

我想用& 替换我的std::string 中出现的所有&。这是代码sn-p 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;
}

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

【问题讨论】:

标签: c++ string c++11 replace stdstring


【解决方案1】:

regex replace 可以使这更容易:

#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;
}

【讨论】:

  • 谢谢,这有帮助 :) 赞成并被接受为答案 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 2017-02-18
  • 1970-01-01
  • 2021-06-15
  • 2021-12-01
  • 1970-01-01
相关资源
最近更新 更多