/******************************************************************************* * * K&R exercise 3-3 * expand - when it appears between lists such as a-z A-Z and 1-9. Ignore all * illogical expansions and print "-" when it appears in such cases. * * program: expand * by.....: yetimach * date...: 4 November 2024 * * ****************************************************************************/ #include #include #include #define MAX 100 char gs1[MAX]; /* global string */ char gs2[MAX]; /* global string */ void expand(char s1[], char s2[]){ int i, j, c, nc, sc, ec; /* new char, start char, end char */ i = j = 0; int add = 1; while ((c = s1[i++]) != '\0' && i < MAX-1 && j < MAX-1){ if (c != '-') s2[j++] = c; else{ if (i-1 != 0){ sc = s1[i-2]; ec = s1[i]; if (((isalpha(sc) && isalpha(ec)) || (isdigit(sc) && isdigit(ec))) && (sc < ec)){ while ((nc = sc + add++) < ec && c != '\0' && i < MAX-1 && j < MAX-1) s2[j++] = nc; add = 1; } }else s2[j++] = c; } } s2[j] = '\0'; return; } void read_line(char string[], int max){ int c, i = 0; while (i < max-1 && (c = getchar()) != '\n' && c != EOF) string[i++] = c; } int main(void) { printf("Enter a string: "); read_line(gs1, MAX); expand(gs1, gs2); printf("\nThe expanded string: %s.\n", gs2); return 0; }