C++ Boost Replace_All Quote
I Have a Problem with Boost: :Replace_All. My String Looks Like: ""Date"":1481200838,""Message"":"" and I Would Like It to Look Like...
I have a problem with boost::replace_all. My string looks like:
""Date"":1481200838,""Message"":""
And I would like it to look like:
"Date":1481200838,"Message":"
So i would like to replace "" with single ":
boost::replace_all(request_json_str, """", """);
But it doesn't work at all. Same with:
boost::replace_all(request_json_str, "\"\"", "\"");
How could I make this to work?
2 Answers
You need to correctly escape the " character in your call to boost::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;
}
The boost::replace_all(request_json_str, "\"\"", "\"") already in your answer is the correct way to handle this using boost::replace_all:
I wanted to post an additional answer to say that given auto request_json_str = "\"\"Date\"\":1481200838,\"\"Message\"\":\"\""s the repeated quotations could also be removed without Boost (though not quite so eloquently, using unique, distance, and string::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 == '"'; })));