IMHO,C++逃脱sequencies是很容易更换他们手动
string string_replace(const string & s, const string & findS, const std::string & replaceS)
{
string result = s;
auto pos = s.find(findS);
if (pos == string::npos) {
return result;
}
result.replace(pos, findS.length(), replaceS);
return string_replace(result, findS, replaceS);
}
string parse(const string& s) {
static vector< pair< string, string > > patterns = {
{ "\\\\" , "\\" },
{ "\\n", "\n" },
{ "\\r", "\r" },
{ "\\t", "\t" },
{ "\\\"", "\"" }
};
string result = s;
for (const auto & p : patterns) {
result = string_replace(result, p.first, p.second);
}
return result;
}
int main() {
string s1 = R"(hello\n\"this is a string with escape sequences\"\n)";
string s2 = "hello\n\"this is a string with escape sequences\"\n";
cout << parse(s1) << endl;
cout << (parse(s1) == s2) << endl;
}
输出:
你好 “这是与转义序列的字符串”
http://ideone.com/jMAfRK
您需要列出解析的所有规则以方便编写parse()函数。 – gman
原始序列或否,解析算法是相同的。 – user1095108
@gman规则与C++字符串文字转义序列的规则相同 – goodbyeera