Skip to content

Instantly share code, notes, and snippets.

@fowlmouth
Created November 7, 2019 13:31
Show Gist options
  • Save fowlmouth/3f0f302a960ae14efda44704cf097bff to your computer and use it in GitHub Desktop.
Save fowlmouth/3f0f302a960ae14efda44704cf097bff to your computer and use it in GitHub Desktop.
#include <string>
#include <vector>
#include <utility>
void gsub(std::string& str, std::vector< std::pair< std::string, std::string >> substitutions)
{
for(const auto& sub : substitutions)
{
const std::string& from = sub.first;
const std::string& to = sub.second;
for(std::size_t i = 0; i < str.size(); )
{
i = str.find(from, i);
if(i != std::string::npos)
{
str.replace(i, from.size(), to);
i += to.size();
}
}
}
}
#include <cassert>
void test_gsub()
{
std::string json = R"json({"x": 1, "b": "yolo'n't"})json";
gsub(json, { {"\"", "\\\""}, {"'", "\\'"} });
assert(json == "{\\\"x\\\": 1, \\\"b\\\": \\\"yolo\\'n\\'t\\\"}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment