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