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

标签 c delphi string

我正在尝试编写一个函数,将 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/

相关文章:

c - C auto 关键字用在哪里?

c - 如何在 C 中对结构数组进行排序?

c - 为什么这些构造使用增量前和增量后未定义的行为?

delphi - 恢复 "lost"D2010 IDE

javascript - 如何使用 Smarty 将带有换行符的文本转换为 JavaScript 换行符

string - 从内存中的字符串加载 node.js 模块

c - url在c中编码一个utf-8字符串?

forms - Delphi:透明或渐变框架

Delphi列表框拖放多个项目

com - 空 BSTR 和 NULL BSTR 之间应该有区别吗?