C++提升报价replace_all

C++ boost replace_all quote

本文关键字:replace all C++      更新时间:2023-10-16

我对boost::replace_all有问题。我的字符串看起来像:

">

"日期":1481200838,"消息":">

我希望它看起来像:

"日期":1481200838,"消息":">

所以我想用单"替换""

boost::replace_all(request_json_str, """", """);

但它根本不起作用。与:

boost::replace_all(request_json_str, """", """);

我怎样才能使它工作?

您需要正确转义调用中的"字符以提升::replace_all!

// Example program
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/algorithm/string/replace.hpp>
int main()
{
std::string msg(""Date"":1481200838,""Message"":"");
boost::replace_all(msg, """", """);
std::cout << msg << std::endl;
}

答案中已有的boost::replace_all(request_json_str, """", """)是使用boost::replace_all处理此问题的正确方法:http://coliru.stacked-crooked.com/a/af7cbc753e16cf4f

我想发布一个额外的答案,说鉴于auto request_json_str = """Date"":1481200838,""Message"":"""s重复的引号也可以在没有 Boost 的情况下删除(尽管不是那么雄辩,使用uniquedistancestring::resize):

request_json_str.resize(distance(begin(request_json_str), unique(begin(request_json_str), end(request_json_str), [](const auto& a, const auto& b){ return a == '"' && b == '"'; })));