#include stdio.h#define MAXLINE 1000int getchars(char line[], int maxline);void escape(char s[], char t[]);
编程学习网为您整理以下代码实例,主要实现:将换行符和制表符等字符转换为可见的转义序列,如\n和\t,希望可以帮到各位朋友。
#include <stdio.h>
#define MAXliNE 1000
int getchars(char line[], int maxline);
voID escape(char s[], char t[]);
voID unescape(char s[], char t[]);
int main(voID){
char t[MAXliNE] = "this is \na \ttest\" test \v test \r ";
char s1[MAXliNE];
char s2[MAXliNE];
escape(s1, t);
printf("\nescape result:\n%s\n", s1);
unescape(s2, s1);
printf("unescape result:\n%s\n", s2);
return 0;
}
voID escape(char s[], char t[]){
int i, j;
for (i = 0, j = 0; t[i] != '\0'; ++i) {
switch (t[i]) {
case '\n':
s[j++] = '\\';
s[j++] = 'n';
break;
case '\t':
s[j++] = '\\';
s[j++] = 't';
break;
case '\v':
s[j++] = '\\';
s[j++] = 'v';
break;
case '\b':
s[j++] = '\\';
s[j++] = 'b';
break;
case '\r':
s[j++] = '\\';
s[j++] = 'r';
break;
case '\f':
s[j++] = '\\';
s[j++] = 'f';
break;
case '\a':
s[j++] = '\\';
s[j++] = 'a';
break;
case '\\':
s[j++] = '\\';
s[j++] = '\\';
break;
case '\?':
s[j++] = '\\';
s[j++] = '\?';
break;
case '\'':
s[j++] = '\\';
s[j++] = '\'';
break;
case '\"':
s[j++] = '\\';
s[j++] = '\"';
break;
default:
s[j++] = t[i];
break;
}
}
s[j] = '\0';
}
voID unescape(char s[], char t[])
{
int i, j;
for (i = 0, j = 0; t[i] != '\0'; ++i) {
if (t[i] == '\\') {
switch (t[++i]) {
case 'n':
s[j++] = '\n';
break;
case 't':
s[j++] = '\t';
break;
case 'v':
s[j++] = '\v';
break;
case 'b':
s[j++] = '\b';
break;
case 'r':
s[j++] = '\r';
break;
case 'f':
s[j++] = '\f';
break;
case 'a':
s[j++] = '\a';
break;
case '\\':
s[j++] = '\\';
break;
case '\?':
s[j++] = '\?';
break;
case '\'':
s[j++] = '\'';
break;
case '\"':
s[j++] = '\"';
break;
// actually, cases below should never happen if the input string is correct.
case '\0':
default:
s[j++] = '\\';
--i;
break;
}
} else {
s[j++] = t[i];
}
}
s[j] = '\0';
}
沃梦达教程
本文标题为:将换行符和制表符等字符转换为可见的转义序列
基础教程推荐
猜你喜欢
- 初始化变量和赋值运算符 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- C++ #define 1970-01-01
- C++定义类对象 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- C语言访问数组元素 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- C++按值调用 1970-01-01