2011-02-24 165 views
1

我想写一个函数来将德尔福/帕斯卡字符串文字转换为C等效。在Delphi中字符串文字的正则表达式("#"([0-9]{1,5}|"$"[0-9a-fA-F]{1,6})|"'"([^']|'')*"'")+匹配使带子德尔福/帕斯卡尔字符串文字到C/C++

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

将在帕斯卡写成

'This is a test with a tab'#9'a breakline'#$A'and apostrophe ''' 

我设法剥离撇号,但我无法管理的特殊字符。

+1

你尝试写一个解析器? – 2011-02-24 20:00:10

+0

你到底是什么?这是一个“C”程序吗?一个“Delphi的例程呢?正则表达式? – 2011-02-24 20:02:38

+0

@ignacio它实际上是一个更大的解析器的一部分,我非常希望不必为这些字符串编写另一个。 @Cosmin我正在寻找一个C++功能是这样的。 – Sambatyon 2011-02-24 20:17:51

回答

1

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

其实,我想要做的是相反的,在CI中有'''这是一个测试'#'''breakline'#$ A'和撇号'''“'我想获得'”这是一个带有tab \ ta breakline \ n和撇号的测试'“' – Sambatyon 2011-02-28 19:49:16