练习3-2 编写一个函数escape(s,t),将字符串t复制到字符串s中,并在复制过程中将换行符、制表符等不可见字符转换为n、t等相应的可见的转义字符序列。要求使用switch语句。

    xiaoxiao2022-06-24  45

    练习3-2 编写一个函数escape(s,t),将字符串t复制到字符串s中,并在复制过程中将换行符、制表符等不可见字符转换为\n、\t等相应的可见的转义字符序列。要求使用switch语句。再编写一个具有相反功能的函数,在复制过程中将转移字符序列转换为实际字符。

    参考代码如下:

    #include<stdio.h> void escape(char s[], char t[]) { int i, j; for(i = j = 0; t[i] != '\0'; i++) switch(t[i]){ case '\n': s[j++] = '\\'; s[j++] = 'n'; break; case '\t': s[j++] = '\\'; s[j++] = 't'; break; default: s[j++] = t[i]; break; } s[j] = '\0'; } void unescape(char s[], char t[]) { int i, j; for(i = j = 0; t[i] != '\0'; i++) { switch (t[i]){ case '\\': switch (t[++i]){ case 'n': s[j++] = '\n'; break; case 't': s[j++] = '\t'; break; default: s[j++] = '\\'; s[j++] = t[i]; } break; default: s[j++] = t[i]; break; } } s[j] = '\0'; } int main() { char t[] = "abcabc\nabcabc"; char s[20]; escape(s, t); printf("%s\n", s); unescape(t, s); printf("%s\n", t); return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-1123790.html

    最新回复(0)