-
Notifications
You must be signed in to change notification settings - Fork 1
/
2.c
99 lines (85 loc) · 2.06 KB
/
2.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
/* Defining a maximum size to strings */
#define SIZE 999
/**
* A function that converts characters like newline and tab into visible escape
* sequences like \n and \t as it copies the string t to s.
*
* @param char[] s String to be copied to
* @param char[] t Source string
*
* @return void
*/
void escape(char s[], char t[])
{
int i = 0;
int j = 0;
char c;
while ((c = t[i++]) != '\0') {
switch (c) {
case '\n':
s[j++] = '\\';
s[j++] = '\\';
s[j++] = 'n';
break;
case '\t':
s[j++] = '\\';
s[j++] = '\\';
s[j++] = 't';
break;
default:
s[j++] = c;
break;
}
}
/* Adding null character */
s[j] = '\0';
return;
}
/**
* A function that converts visible escape sequences like \n and \t into
* characters like newline and tab as it copies the string t to s.
*
* @param char[] s String to be copied to
* @param char[] t Source string
*
* @return void
*/
void escape_back(char s[], char t[])
{
int i = 0;
int j = 0;
char c;
while ((c = t[i++]) != '\0') {
switch (c) {
case '\\':
if (t[i] == '\\' && t[i+1] == 'n') {
s[j++] = '\n';
} else if (t[i] == '\\' && t[i+1] == 't') {
s[j++] = '\t';
}
i += 2;
break;
default:
s[j++] = c;
break;
}
}
/* Adding null character */
s[j] = '\0';
return;
}
/**
* A program to test string copying.
* For the sake of simplicity, we assume only '\t' and '\n' can be scaped.
*/
main()
{
char input1[SIZE] = "A \n test \t whatever.";
char output1[SIZE];
char output2[SIZE];
escape(output1, input1);
printf("escape('%s') => '%s'\n", input1, output1);
escape_back(output2, output1);
printf("escape_back('%s') => '%s'\n", output1, output2);
}