編一個函數escape(s,t),將字符串t複製到s中,並在複製過程中將換行符、製表符轉換成\n\t可見字符。
再編寫一個具有相反功能的函數。
代碼:
#include <stdio.h>
#include <stdlib.h>
void escape(char *s, const char *t);
void rescape(char *s, const char *t);
int main(int argc, char *argv[])
{
char s[30] = "";
char t[20] = "hello world\\t!\\n";
escape(s, t);
rescape(s, t);
printf("%s", s);
return 0;
}
void escape(char *s, const char *t)
{
size_t j = 0;
for (size_t i = 0; t[i] != '\0'; ++i) {
switch (t[i]) {
case '\t':
{
s[j++] = '\\';
s[j++] = 't';
break;
}
case '\n':
{
s[j++] = '\\';
s[j++] = 'n';
break;
}
case ' ':
{
s[j++] = '#';
break;
}
default:
s[j++] = t[i];
}
}
s[j++] = '\0';
}
void rescape(char *s, const char *t)
{
size_t j = 0;
for (size_t i = 0; t[i] != '\0'; ++i) {
switch (t[i]) {
case '\\':
{
if (t[i+1] == 't') {
++i;
s[j++] = '\t';
} else if (t[i+1] == 'n') {
++i;
s[j++] = '\n';
} else {
s[j++] = '\\';
}
}
break;
default:
{
s[j++] = t[i];
}
}
}
s[j++] = '\0';
}