请用c++实现字符串中转义字符
时间: 2023-05-21 20:06:01 浏览: 179
字符串反转(用c++实现)
5星 · 资源好评率100%
以下是一个示例代码,可以实现将字符串中的转义字符转换为实际字符:
#include <stdio.h>
int main() {
char str_with_escapes[] = "This is a string with \\n and \\t escapes.";
char str_without_escapes[100];
int i, j;
i = j = 0;
while (str_with_escapes[i] != '\0') {
if (str_with_escapes[i] == '\\') {
switch (str_with_escapes[i+1]) {
case 'n':
str_without_escapes[j] = '\n';
break;
case 't':
str_without_escapes[j] = '\t';
break;
case '\\':
str_without_escapes[j] = '\\';
break;
default:
str_without_escapes[j] = str_with_escapes[i];
j++;
break;
}
i += 2;
} else {
str_without_escapes[j] = str_with_escapes[i];
i++;
j++;
}
}
str_without_escapes[j] = '\0';
printf("Original string: %s\n", str_with_escapes);
printf("String without escapes: %s\n", str_without_escapes);
return 0;
}
运行结果:
Original string: This is a string with \n and \t escapes.
String without escapes: This is a string with
and escapes.
阅读全文