如何用转义符替换字符串中的所有特殊字符
How do I replace all special characters in a string with the escape character?
如果我有一个看起来像"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
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 转义std::字符串中的特殊字符
- 使用具有特殊字符的正则表达式标记 C++ 字符串
- 如何输入以特殊字符开头的字符串
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- 将mysqlx :: value转换为带有特殊字符的std ::字符串
- 如何检查字符串中的特殊字符
- 带有特殊字符的字符串的控制台输出
- 使用迭代器从字符串中删除特殊字符
- C 中的特殊字符的子字符串(STD :: substr)
- 如何使用嵌套的getline()函数来获取字符串中的特殊字符和标点符号
- C++:比较字符串或包含特殊字符(á、é、ő 等)的字符串或 wstring )
- 字符串到字符*的特殊字符转换
- python字符串使用特殊字符发送到c++dll,崩溃
- 字符串本地化缺少一些特殊字符
- C++ 标识字符串中的特殊字符
- 反转字符串中的每个字符,特殊字符除外(例如 "?" )
- 在VC ++浮点数据类型值中,如何检查字符串或特殊字符是否混合