Exercise 3-3 (Expand shorthand notation)

Chapter_3     Exercise_3-2     shellsort Exercise_3-4







Exercise 3-3     K&R, p. 63


Exercise 3-3. Write a function expand(s1,s2) that expands shorthand notations like a-z in the string s1 into the equivalent complete list abc...xyz in s2. Allow for letters of either case and digits, and be prepared ho handle cases like a-b-c, a-z0-9, and -a-z. Arrange that a leading or trailing - is taken literally.




expand.c         download


#include <stdio.h> // for printf(), scanf()

#define SIZE 100 // array size

void expand(char [], char []); // expand a-z A-Z 0-9

int main()
{
char s1[SIZE], s2[SIZE*10];

printf("Type a word with unexpanded sequences like a-z A-Z 0-9:\n");
scanf("%s", s1);

expand(s1, s2);
printf("%s\n", s2);

return 0;
}

void expand(char s[], char t[]) // expand a-z A-Z 0-9
{
int i, j = 0, k;

for (i = 0; s[i] != '\0'; i++)
{
if (s[i] == '-')
{
if (i > 0 && s[i-1] >= '0' && s[i-1] <= '9' && s[i+1] > s[i-1] && s[i+1] <= '9')
{
for (k = s[i-1]+1; k <= s[i+1]; k++)
{t[j++] = k;}
i++;
}
else if (i > 0 && s[i-1] >= 'a' && s[i-1] <= 'z' && s[i+1] > s[i-1] && s[i+1] <= 'z')
{
for (k = s[i-1]+1; k <= s[i+1]; k++)
{t[j++] = k;}
i++;
}
else if (i > 0 && s[i-1] >= 'A' && s[i-1] <= 'Z' && s[i+1] > s[i-1] && s[i+1] <= 'Z')
{
for (k = s[i-1]+1; k <= s[i+1]; k++)
{t[j++] = k;}
i++;
}
else {t[j++] = s[i];}
}
else {t[j++] = s[i];}
}
t[j] = '\0';
}
/*
gcc expand.c -o expand
./expand
-a-t+A-f+a-G+A-B-A-C+Z-T+1-8-
-abcdefghijklmnopqrst+A-f+a-G+AB-ABC+Z-T+12345678-
*/









Chapter_3     Exercise_3-2     shellsort BACK_TO_TOP Exercise_3-4



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo