这个例子把string字符串中的 " 替换成"
原作者Michael Mrozek ,在stackoverflow找到的https://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string
#include <iostream>
using namespace std;
#include <string>
#include<string.h>
#include "json.hpp"
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
int main(){
std::string string(R"({"to_groupid":"ui","type":
"TEXT","data":{"type":"alarm","workmode":"mode_gr"},"total":1,"current":0,"pc":"0.997997"})");
replaceAll(string, "\"", "\\\"");
cout << string << endl;
return 0;
}