Blob


1 /*
2 * Exercise 3-3. Write a function expand(s1, s2) that expands shorthand
3 * notations like a-z in the string s1 into the equivalent complete list
4 * abc...xyz in s2. Allow for letters of either case and digits, and be
5 * prepared to handle cases like a-b-c and a-z0-9 and -a-z. Arrange that
6 * a leading or trailing - is taken literally.
7 */
9 #include <stdio.h>
11 int expand(char *s1, char *s2);
13 int main()
14 {
15 char expansion[200];
16 expand("a-z", expansion);
17 printf("Expect: abcdefghijlkmnopqrstuvwxyz\n");
18 printf("Result: %s\n", expansion);
19 expand("A-Z", expansion);
20 printf("Expect: ABCDEFGHIJLKMNOPQRSTUVWXYZ\n");
21 printf("Result: %s\n", expansion);
22 expand("0-9", expansion);
23 printf("Expect: 0123456789\n");
24 printf("Result: %s\n", expansion);
25 expand("a-z0-9", expansion);
26 printf("Expect: abcdefghijlkmnopqrstuvwxyz0123456789\n");
27 printf("Result: %s\n", expansion);
28 expand("-a-z", expansion);
29 printf("Expect: -abcdefghijlkmnopqrstuvwxyz\n");
30 printf("Result: %s\n", expansion);
31 expand("a-b-c", expansion);
32 printf("Expect: abc\n");
33 printf("Result: %s\n", expansion);
34 return 0;
35 }
37 /* return value is number of expansions */
38 int expand(char *s1, char *s2) {
39 int expansions = 0;
40 char prev = '\0';
41 char next;
42 while (*s1) {
43 if (*s1 == '-') {
44 next = *(s1+1);
45 if ((prev >= 'a' && next <= 'z') ||
46 (prev >= 'A' && next <= 'Z') ||
47 (prev >= '0' && next <= '9')) {
48 prev++; /* first letter copied by default */
49 expansions++;
50 while (prev < next) { /* last letter copied by default */
51 *s2++ = prev++;
52 }
53 s1++;
54 }
55 }
56 prev = *s2++ = *s1++;
57 }
58 *s2 = '\0';
59 return expansions;
60 }