将字符串1复制给字符串2,在复制过程中将换行符制表符等转换为\n,\t;
#include<stdio.h>
#include<malloc.h>
void unescape(char *str1, char *str2) {
int i = 0;
int j = 0;
while (str1[i] != '\0') {
if (str1[i] == '\\') {
switch(str1[i + 1]) {
case 't':
str2[j++] = '\t';
i++;
break;
case 'n':
str2[j++] = '\n';
i++;
break;
default:
str2[j++] = str1[i];
break;
}
i++;
}
else {
str2[j++] = str1[i];
i++;
}
}
str2[j] = '\0';
}
void escape(char *str1, char *str2) {
int i = 0;
int j = 0;
while (str1[i] != '\0') {
switch (str1[i]) {
case '\t':str2[j++] = '\\'; str2[j++] = 't';
break;
case '\n':str2[j++] = '\\'; str2[j++] = 'n';
break;
default:
str2[j++] = str1[i];
break;
}
i++;
}
str2[j] = '\0';
}
int main() {
char * str1= "we are friends\nye\thaha haha\thao hao";
char *str2=NULL;
char *str3 = NULL;
str2 = (char*)malloc(2*sizeof(str1));
str3 = (char*)malloc(2*sizeof(str1));
printf("please input the string str1:\n%s\n",str1);
escape(str1, str2);
printf("the str2 is:\n");
printf("%s\n",str2);
unescape(str2, str3);
printf("the str3 is:\n");
printf("%s\n", str3);
return 0;
}
注意’\t’转译以后为两个字符\和t;