gpt4 book ai didi

c++ - 如何用实际值替换转义符号?

转载 作者:行者123 更新时间:2023-12-03 07:21:51 26 4
gpt4 key购买 nike

我有一个像escape new lines\n这样的字符串。打印时,它不会用新行替换\n,而只是打印escape new lines\n。我正在遍历这个std::string,我想用它的实际值替换\n:

bool seenSlash = false;
for (int index = 0; index < text.length(); ++index) {
if (text[index] == '\\') {
seenSlash = true;
continue;
}
if (seenSlash) {
// what to do here?
seenSlash = false;
}
}
不只是 \n,我想支持所有这些转义符号。我该怎么做?

最佳答案

您可以做的是switch语句或使用常量std::map<char,char>:

if (seenSlash) {
bool replace = false;
switch(text[index]) {
case 'n':
replace = true;
text[index-1] = '\n';
break;
case 't':
replace = true;
text[index-1] = '\t';
break;
// ... etc.
}
if(replace) {
text.erase(text.begin() + index); // erase the cuurent char, the
// backslash char was replaced
--index; // adapt the index for the next iteration
}
seenSlash = false;
}
const std::map<char,char> escaped_chars = {
{ 'n', '\n' } ,
{ 't', '\t' } ,
{ 'a', '\a' } ,
// ... etc.
};

if (seenSlash) {
bool replace = escaped_chars.find(text[i]) != escaped_chars.end();
if(replace) {
text[index - 1] = escaped_chars[text[i]];
text.erase(text.begin() + index); // erase the cuurent char, the
// backslash char was replaced
--index; // adapt the index for the next iteration
}
seenSlash = false;
}

关于c++ - 如何用实际值替换转义符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64882339/

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