gpt4 book ai didi

c - Delphi/Pascal 字符串文字到 C/C++

转载 作者:太空宇宙 更新时间:2023-11-04 04:06:50 24 4
gpt4 key购买 nike

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

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

将用 Pascal 编写为

'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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com