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:

"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?

5

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

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 == '"'; })));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest