#include "stdafx.h"
#include <string>
#include <stdarg.h>
#include <memory>
#include <iostream>
#include <map>
using namespace std;
namespace {
string StringReplace(const string& str_src, const string& from, const string& to) {
if (str_src.empty()
|| from.empty()
|| to.empty())
{
return str_src;
}
string str_dst;
string str_src_tmp = str_src;
size_t from_size = from.size();
size_t to_size = to.size();
// 循环处理未处理字符串
for (size_t pos = str_src_tmp.find(from); string::npos != pos; pos = str_src_tmp.find(from))
{
str_src_tmp.replace(pos, from_size, to); // 替换from到to
str_dst += str_src_tmp.substr(0, from_size + pos); // 获取已处理字符串
str_src_tmp = str_src_tmp.substr(from_size + pos); // 获取未处理字符串
}
// 拼接剩余字符串
str_dst += str_src_tmp;
return str_dst;
}
}
/**
* Json文档中,如果内容包含某些特殊字符会导致Json文件无法解析,需要对内容做转义处理。
转义字符 含义
\" 双引号
\\ 反斜杠
\/ 正斜杠
\b 退格
\f 换页
\n 换行
\r 回车
\t 制表符
*/
string StringEscapeForJson(const string& str_src) {
if (str_src.empty()) {
return str_src;
}
string str_dst = str_src;
static map<char, string> map_special = {
{ '"', "\\\"" },
{ '\\', "\\\\" },
{ '/', "\\/" },
{ '\b', "\\b" },
{ '\f', "\\f" },
{ '\n', "\\n" },
{ '\r', "\\r" },
{ '\t', "\\t" },
{ '\0', "\\0" },
};
size_t size = str_dst.size();
for (size_t pos = 0; pos < size;) {
char c = str_dst.at(pos);
auto iter_c = map_special.find(c);
if (map_special.end() != iter_c)
{
str_dst.replace(pos, 1, iter_c->second);
pos += iter_c->second.size();
size += iter_c->second.size() - 1;
continue;
}
++pos;
}
return str_dst;
}
int main() {
string str_json = "|abc|\b|'|\"|<|\\|";
string str_json_escape = StringEscapeForJson(str_json);
getchar();
return 0;
}
Json特殊字符转义
最新推荐文章于 2024-06-07 07:16:31 发布