如何用转义符替换字符串中的所有特殊字符

How do I replace all special characters in a string with the escape character?

本文关键字:特殊字符 字符串 何用 转义 替换      更新时间:2023-10-16

如果我有一个看起来像"A\nB"的字符串,我如何将其转换为"AnB"

n部分应作为一条新线使用。它不应该打印"A\nB",它应该打印如下:

A
B

您可以创建一个单独的函数,通过以下方式从std::string中删除转义字符:

std::string remove_escape_char(std::string const& s) {
std::string result;
auto it = s.begin();
while (it != s.end()) {
char c = *it++;
if (c == '' && it != s.end()) {
switch (*it++) {
case '':
c = '';
break;
case 'n':
c = 'n';
break;
default: 
continue;
}
}
result += c;
}
return result;
}

然后从std::string:中删除特殊字符的功能

void remove_special_char(std::string& str, char c) {
auto position = str.find(c);
while (position != std::string::npos) {
str.erase(position, 1);
position = str.find(c);
}
}

您可以使用以上两个功能,如:

std::string str{""A\nB""};
remove_special_char(str, 0x22); // remove "
std::cout << remove_escape_char(str) << std::endl;

现在的输出应该是:

A
B

演示

这应该完成以下工作:

if(example.size() > 1) {
for (auto i = 0ul; i < example.size() - 1; ++i) // loop through the string char by char
if (example[i] != '' || (example[i + 1] == ''))
result += example[i]; // if the current one is a  and the next char is different to  (for the case of \) remove it
if (example[example.size() - 1] == '' && example[example.size() - 1] == '') result += ''; // check for the last char
} else if(example.size() == 1 && example[0] != '') result+=example[0]; // check for special case there the string is just one char long