#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';
}
沃梦达教程
本文标题为:将换行符和制表符等字符转换为可见的转义序列
猜你喜欢
- 使用整数值初始化char类型的变量 1970-01-01
- 使用来自float.h和limits的数据,找到该系统的一些 1970-01-01
- C++指向数组的指针 1970-01-01
- 运算符优先级 1970-01-01
- 打印扩展的ASCII字符 1970-01-01
- C语言可使用的所有转义序列 1970-01-01
- C语言求模 1970-01-01
- C++浮点常数 1970-01-01
- 使用最流行的转义序列 1970-01-01
- “纯虚函数调用"在哪里?崩溃从何而来? 2022-10-18