我正在尝试编写一个函数,将Delphi/pascal中的字符串文字转换为C等价物。Delphi中的字符串文本与regex("#"([0-9]{1,5}|"$"[0-9a-fA-F]{1,6})|"'"([^']|'')*"'")+匹配,以便

"This is a test with a tab\ta breakline\nand apostrophe '"

将用帕斯卡语写成
'This is a test with a tab'#9'a breakline'#$A'and apostrophe '''

我设法去掉了撇号,但我在处理特殊字符时遇到了困难。

最佳答案

只需使用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;

关于c - Delphi/Pascal字符串文字转换为C/C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5109748/

10-11 22:38
查看更多