Skip to content

Commit 509aa60

Browse files
committed
3.4
1 parent b4dbed8 commit 509aa60

File tree

3 files changed

+147
-0
lines changed

3 files changed

+147
-0
lines changed

chapter-3-control-flow/2.switch.c

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <stdio.h>
2+
3+
main()
4+
{
5+
int c, i, nwhite, nother, ndigit[10];
6+
7+
nwhite = nother = 0;
8+
for (i = 0; i < 10; i++)
9+
ndigit[i] = 0;
10+
11+
while ((c = getchar()) != EOF) {
12+
switch(c) {
13+
case '0': case '1': case '2': case '3': case '4':
14+
case '5': case '6': case '7': case '8': case '9':
15+
ndigit[c-'0']++;
16+
break;
17+
case ' ':
18+
case '\n':
19+
case '\t':
20+
nwhite++;
21+
break;
22+
default:
23+
nother++;
24+
break;
25+
}
26+
}
27+
printf("digits = ");
28+
for (i = 0; i < 10; i++)
29+
printf(" %d", ndigit[i]);
30+
printf(", white space = %d, other = %d\n",
31+
nwhite, nother);
32+
return 0;
33+
}

chapter-3-control-flow/3.escape.c

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <stdio.h>
2+
3+
#define MAX_LEN 1000
4+
5+
void escape(char[], char[]);
6+
7+
main()
8+
{
9+
char t[] = "Hello\tWorld\r\n\v";
10+
printf("%s\n", t);
11+
char s[MAX_LEN];
12+
escape(s, t);
13+
printf("%s\n", s);
14+
}
15+
16+
void escape(char s[], char t[])
17+
{
18+
int i, j, n;
19+
for (i = 0, j = 0; t[j] != '\0'; i++, j++) {
20+
switch(t[j]) {
21+
case '\a':
22+
s[i++] = '\\';
23+
n = 'a';
24+
break;
25+
case '\b':
26+
s[i++] = '\\';
27+
n = 'b';
28+
break;
29+
case '\f':
30+
s[i++] = '\\';
31+
n = 'f';
32+
break;
33+
case '\n':
34+
s[i++] = '\\';
35+
n = 'n';
36+
break;
37+
case '\r':
38+
s[i++] = '\\';
39+
n = 'r';
40+
break;
41+
case '\t':
42+
s[i++] = '\\';
43+
n = 't';
44+
break;
45+
case '\v':
46+
s[i++] = '\\';
47+
n = 'v';
48+
break;
49+
default:
50+
n = t[j];
51+
break;
52+
}
53+
s[i] = n;
54+
}
55+
s[i] = '\0';
56+
}

chapter-3-control-flow/4.unescape.c

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <stdio.h>
2+
3+
#define MAX_LEN 1024
4+
5+
void unescape(char[], char[]);
6+
7+
main()
8+
{
9+
char t[] = "Hello\\tWorld!!!\\r\\nEOF\\v";
10+
printf("%s\n", t);
11+
char s[MAX_LEN] = "";
12+
unescape(s, t);
13+
printf("%s\n", s);
14+
}
15+
16+
void unescape(char s[], char t[])
17+
{
18+
int i, j, n;
19+
20+
for (i = 0, j = 0; t[j] != '\0'; i++, j++) {
21+
if (t[j] == '\\' && t[j+1] != '\0') {
22+
j++;
23+
24+
switch(t[j]) {
25+
case 'a':
26+
s[i] = '\a';
27+
break;
28+
case 'b':
29+
s[i] = '\b';
30+
break;
31+
case 'f':
32+
s[i] = '\f';
33+
break;
34+
case 'n':
35+
s[i] = '\n';
36+
break;
37+
case 'r':
38+
s[i] = '\r';
39+
break;
40+
case 't':
41+
s[i] = '\t';
42+
break;
43+
case 'v':
44+
s[i] = '\v';
45+
break;
46+
default:
47+
s[i++] = '\\';
48+
s[i] = t[j];
49+
break;
50+
}
51+
} else {
52+
s[i] = t[j];
53+
}
54+
}
55+
56+
s[i] = '\0';
57+
}
58+

0 commit comments

Comments
 (0)