[英]How do I replace all special characters in a string with the escape character?
If I had a string that looked like \\"A\\\\nB\\"
, how do I transform it to look like "A\\nB"
?如果我有一个看起来像\\"A\\\\nB\\"
的字符串,我如何将它转换为看起来像"A\\nB"
?
The \\n
portion should work as a new line. \\n
部分应该作为一个新行。 It should not be printing "A\\nB", it should be printing as follows:它不应该打印“A\\nB”,它应该打印如下:
A
B
This should do the work:这应该做的工作:
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
You can create a separate function for removing escape characters from your std::string
in a following way:您可以通过以下方式创建一个单独的函数来从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;
}
and then the function for removing special characters from std::string
:然后是从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);
}
}
You can use above two functions like:您可以使用以上两个功能,例如:
std::string str{"\"A\\nB\""};
remove_special_char(str, 0x22); // remove "
std::cout << remove_escape_char(str) << std::endl;
Now the output should be:现在输出应该是:
A
B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.