Created
November 5, 2009 13:00
-
-
Save shaobin0604/227033 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 t to s. Use a switch. Write a function for the other direction | |
* as well, converting escape sequences into the real characters. | |
*/ | |
#include <stdio.h> | |
#define MAXLEN 1000 | |
int escape(char s[], const char t[]); | |
int unescape(char s[], const char t[]); | |
int escape(char s[], const char t[]) { | |
int i = 0, j = 0, count = 0; | |
while (t[i] != '\0') { | |
switch (t[i]) { | |
case '\n': | |
s[j++] = '\\'; | |
s[j++] = 'n'; | |
count++; | |
break; | |
case '\t': | |
s[j++] = '\\'; | |
s[j++] = 't'; | |
count++; | |
break; | |
default: | |
s[j++] = t[i]; | |
break; | |
} | |
i++; | |
} | |
s[j] = '\0'; | |
return count; | |
} | |
int unescape(char s[], const char t[]) { | |
int i = 0, j = 0, count = 0; | |
while (t[i] != '\0') { | |
if (t[i] == '\\') { | |
switch (t[++i]) { | |
case 't': | |
s[j++] = '\t'; | |
count++; | |
break; | |
case 'n': | |
s[j++] = '\n'; | |
count++; | |
break; | |
case '\0': | |
s[j++] = '\\'; | |
s[j] = '\0'; | |
return count; | |
default: | |
s[j++] = '\\'; | |
s[j++] = t[i]; | |
break; | |
} | |
} else { | |
s[j++] = t[i]; | |
} | |
i++; | |
} | |
s[j] = '\0'; | |
return count; | |
} | |
int main(void) { | |
char t[] = "fjdla jdja fldjsl fdlsaj\n"; | |
char s[MAXLEN]; | |
char u[MAXLEN]; | |
escape(s, t); | |
unescape(u, s); | |
printf("t -> %s\n", t); | |
printf("s -> %s\n", s); | |
printf("u -> %s\n", u); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment