-
Notifications
You must be signed in to change notification settings - Fork 1
/
escape.c
83 lines (75 loc) · 1.57 KB
/
escape.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <string.h>
#include <assert.h>
/*
Exercise 3-2. Write a function escape(s, t) that converts characters like
newline and tab into visible escape sequences like \n and \t as it copies the
string to s. Use a switch. Write a function for the other direction as well,
converting escape sequences into the real characters.
*/
#define MAX_LINE 1000
void escape(char s[], char t[])
{
int i, j;
int len = strlen(t);
for(i = j = 0; i < len; i++, j++) {
switch(t[i]) {
case '\t':
s[j] = '\\';
s[++j] = 't';
break;
case '\n':
s[j] = '\\';
s[++j] = 'n';
break;
default:
s[j] = t[i];
break;
}
}
s[j] = '\0';
}
void unescape(char s[], char t[])
{
int i, j;
int len = strlen(t);
for(i = j = 0; i < len; i++, j++) {
switch(t[i]) {
case '\\':
if (i < len - 1) {
i++;
switch(t[i]) {
case 't':
s[j] = '\t';
break;
case 'n':
s[j] = '\n';
break;
default:
s[j] = t[i];
break;
}
} else {
assert(0);
}
break;
default:
s[j] = t[i];
break;
}
}
s[j] = '\0';
}
int main()
{
char t[] = "This is line one.\nThis is line two\twith a tab.\nLine three ends with a slash";
char s[MAX_LINE];
char us[MAX_LINE];
printf("t:\n%s\n", t);
printf("\n");
escape(s, t);
printf("s:\n%s\n", s);
printf("\n");
unescape(us, s);
printf("us:\n%s\n", us);
}