分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程
/*
* 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.
* Write a function for the other direction as well, converting escape sequences
* into the real characters.
*
* Escape.c - by FreeMan
*/
#include <stdio.h>
void Escape(char *s, char *t);
void Unescape(char *s, char *t);
int main(void)
{
char s[50] = "\aHello,\n\tWorld! Mistakee\b was \"Extra 'e'\"!\n";
char t[51];
printf("Original string:\n%s\n", s);
Escape(t, s);
printf("Escaped string:\n%s\n", t);
Unescape(s, t);
printf("Unescaped string:\n%s\n", s);
return 0;
}
void Escape(char *s, char *t)
{
int i, j;
i = j = 0;
while (t[i])
{
/* Translate the special character, if we have one */
switch (t[i])
{
case '\n':
s[j++] = '\\';
s[j] = 'n';
break;
case '\t':
s[j++] = '\\';
s[j] = 't';
break;
case '\a':
s[j++] = '\\';
s[j] = 'a';
break;
case '\b':
s[j++] = '\\';
s[j] = 'b';
break;
case '\f':
s[j++] = '\\';
s[j] = 'f';
break;
case '\r':
s[j++] = '\\';
s[j] = 'r';
break;
case '\v':
s[j++] = '\\';
s[j] = 'v';
break;
case '\\':
s[j++] = '\\';
s[j] = '\\';
break;
case '\"':
s[j++] = '\\';
s[j] = '\"';
break;
default:
/* This is not a special character, so just copy it */
s[j] = t[i];
break;
}
++i;
++j;
}
s[j] = t[i]; /* Don't forget the null character */
}
void Unescape(char *s, char *t) {
int i, j;
i = j = 0;
while (t[i]) {
switch (t[i]) {
case '\\':
/* We've found an escape sequence, so translate it */
switch (t[++i]) {
case 'n':
s[j] = '\n';
break;
case 't':
s[j] = '\t';
break;
case 'a':
s[j] = '\a';
break;
case 'b':
s[j] = '\b';
break;
case 'f':
s[j] = '\f';
break;
case 'r':
s[j] = '\r';
break;
case 'v':
s[j] = '\v';
break;
case '\\':
s[j] = '\\';
break;
case '\"':
s[j] = '\"';
break;
default:
/* We don't translate this escape sequence, so just copy it verbatim */
s[j++] = '\\';
s[j] = t[i];
}
break;
default:
/* Not an escape sequence, so just copy the character */
s[j] = t[i];
}
++i;
++j;
}
s[j] = t[i]; /* Don't forget the null character */
}
// Output:
/*
Original string:
Hello,
World! Mistake was "Extra 'e'"!
Escaped string:
\aHello,\n\tWorld! Mistakee\b was \"Extra 'e'\"!\n
Unescaped string:
Hello,
World! Mistake was "Extra 'e'"!
*/