只需使用replaceApp()
功能,可以发现:http://www.cppreference.com/wiki/string/basic_string/replace
然后代码可以作为看:
string s1 = "This is a test with a tab\\ta breakline\\nand apostrophe '";
string s2 = s1;
s2 = replaceAll(s2, "'", "''");
s2 = replaceAll(s2, "\\t", "'$7'");
s2 = replaceAll(s2, "\\n", "'$10'");
cout << "'" << s2 << "'";
当然改变 '\ t' - > '$ 7' 可以保存在一些结构您可以在循环中使用,而不是用单独的行替换每个项目。
编辑:
第二种解决方案(例如,从评论拍摄)使用map
:
typedef map <string, string> MapType;
string s3 = "'This is a test with a tab'#9'a breakline'#$A'and apostrophe '''";
string s5 = s3;
MapType replace_map;
replace_map["'#9'"] = "\\t";
replace_map["'#$A'"] = "\\n";
replace_map["''"] = "'";
MapType::const_iterator end = replace_map.end();
for (MapType::const_iterator it = replace_map.begin(); it != end; ++it)
s5 = replaceAll(s5, it->first, it->second);
cout << "s5 = '" << s5 << "'" << endl;
你尝试写一个解析器? – 2011-02-24 20:00:10
你到底是什么?这是一个“C”程序吗?一个“Delphi的例程呢?正则表达式? – 2011-02-24 20:02:38
@ignacio它实际上是一个更大的解析器的一部分,我非常希望不必为这些字符串编写另一个。 @Cosmin我正在寻找一个C++功能是这样的。 – Sambatyon 2011-02-24 20:17:51