Exercise 3-2 (Escapes conversion)
Chapter_3 Exercise_3-1 count | shellsort Exercise_3-3 |
Exercise 3-2 K&R, p. 60
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.
escapes.c download
#include <stdio.h> // for printf()
#define SIZE 100 // array size
void escape(char s[], char t[]); // copy t[] to s[] making escapes visible
void unescape(char s[], char t[]); // copy t[] to s[] doing the opposite
int main()
{
char s[SIZE];
char t[SIZE] = "\', \", \t, \n, \r, \f, \v, \a, \b, \\, etc.";
printf("String with escapes: %s\n", t);
escape(s,t);
printf("Visible escapes: %s\n", s);
unescape(t,s);
printf("Real characters: %s\n", t);
return 0;
}
void escape(char s[], char t[]) // copy t[] to s[] making escapes visible
{
int i, j = 0;
for (i = 0; t[i] != '\0'; i++)
{
switch(t[i])
{
case '\'' :
s[j++] = '\\'; s[j++] = '\'';
break;
case '\"' :
s[j++] = '\\'; s[j++] = '\"';
break;
case '\t' :
s[j++] = '\\'; s[j++] = 't';
break;
case '\n' :
s[j++] = '\\'; s[j++] = 'n';
break;
case '\r' :
s[j++] = '\\'; s[j++] = 'r';
break;
case '\f' :
s[j++] = '\\'; s[j++] = 'f';
break;
case '\v' :
s[j++] = '\\'; s[j++] = 'v';
break;
case '\a' :
s[j++] = '\\'; s[j++] = 'a';
break;
case '\b' :
s[j++] = '\\'; s[j++] = 'b';
break;
case '\\' :
s[j++] = '\\'; s[j++] = '\\';
break;
default:
s[j++] = t[i]; // copy non-escapes
break;
}
}
s[j] = '\0'; // properly end string
}
void unescape(char s[], char t[]) // copy t[] to s[] turning \t into tab, etc.
{
int i, j = 0;
for (i = 0; t[i] != '\0'; i++)
{
switch(t[i])
{
case '\\' :
switch(t[i+1])
{
case '\'' : case '\"' : case '\\' :
s[j++] = t[i+1];
i++;
break;
case 't' :
s[j++] = '\t';
i++;
break;
case 'n' :
s[j++] = '\n';
i++;
break;
case 'r' :
s[j++] = '\r';
i++;
break;
case 'f' :
s[j++] = '\f';
i++;
break;
case 'v' :
s[j++] = '\v';
i++;
break;
case 'a' :
s[j++] = '\a';
i++;
break;
case 'b' :
s[j++] = '\b';
i++;
break;
default:
s[j++] = t[i];
break;
}
break;
default:
s[j++] = t[i];
break;
}
}
s[j] = '\0'; // properly end string
}
/*
gcc escapes.c -o escapes
./escapes
String with escapes: ', ", ,
,
,
, ,, \, etc.
Visible escapes: \', \", \t, \n, \r, \f, \v, \a, \b, \\, etc.
Real characters: ', ", ,
,
,
, ,, \, etc.
*/
Chapter_3 Exercise_3-1 count | BACK_TO_TOP | shellsort Exercise_3-3 |
Comments
Post a Comment