C++ 在字符串中展开控制字符
在我的应用程序中,我收到如下std::字符串C++ 在字符串中展开控制字符,c++,string,C++,String,在我的应用程序中,我收到如下std::字符串 "12\tcout << \"Text\" << endl;\n" “12\t输出您可以创建一个正则表达式来替换字符,尽管它有点取决于字符串的格式。否则可能更简单,只需按照您自己的建议执行即可 除了逐字符解析字符串并用对应的漂亮打印序列替换每个字符序列之外,还有其他更好的方法吗 不,标准库中没有这样做的功能,但是如果有,它只需逐个字符解析字符串 std::string expand_tabs_and_escapes(std:
"12\tcout << \"Text\" << endl;\n"
“12\t输出您可以创建一个正则表达式来替换字符,尽管它有点取决于字符串的格式。否则可能更简单,只需按照您自己的建议执行即可
除了逐字符解析字符串并用对应的漂亮打印序列替换每个字符序列之外,还有其他更好的方法吗
不,标准库中没有这样做的功能,但是如果有,它只需逐个字符解析字符串
std::string expand_tabs_and_escapes(std::string const& s, int tabstop=8) {
assert(tabstop >= 1);
std::string r;
for (std::string::const_iterator x = s.begin(); x != s.end(); ++x) {
switch (*x) {
case '\\':
if (++x == s.end()) handle_bad_escape();
else {
switch (*x) {
case 't':
goto tab;
case 'n':
r += '\n';
break;
// and so on for other escapes: \, ", r, v, f, etc.
default:
handle_bad_escape();
}
}
break;
case '\t':
tab:
r += std::string(tabstop - (r.size() % tabstop), ' ');
break;
default:
r += *x;
}
}
return r;
}
您还可以将其分解为expand\u转义符(将\t转换为实际选项卡)和expand\u tabs(将所有选项卡转换为空格)。虽然再次读取,但数据中似乎没有转义符(如“\\t”),而是实际的控制字符,因此您只需要上面的expand\u tabs功能
std::string expand_tabs_and_escapes(std::string const& s, int tabstop=8) {
assert(tabstop >= 1);
std::string r;
for (std::string::const_iterator x = s.begin(); x != s.end(); ++x) {
switch (*x) {
case '\\':
if (++x == s.end()) handle_bad_escape();
else {
switch (*x) {
case 't':
goto tab;
case 'n':
r += '\n';
break;
// and so on for other escapes: \, ", r, v, f, etc.
default:
handle_bad_escape();
}
}
break;
case '\t':
tab:
r += std::string(tabstop - (r.size() % tabstop), ' ');
break;
default:
r += *x;
}
}
return r;
}