演習 3-3
無職の間にK&Rを再読。演習問題の解答をさらす。解く順番は適当。
演習 3-3
文字列 s1 中の a-z のような省略記号を、それと等価な完全リスト abc......xyz にして s2 中に展開する関数 expand(s1, s2) を書け。大文字、小文字、数字を許し、a-b-c や a-z0-9 や -a-z のような場合も処理できるようにせよ。先頭および最後の - は文字とみなす。
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 to handle cases like a-b-c and a-z0-9 and -a-z. Arrange that a leading or trailing - is taken literally.
なんか不細工な気もするけど、良しとする。
#include <stdio.h> /* Answer */ void expand(const char s1[], char s2[]) { int i, j, k; for (i = j = 0; s1[i] != '\0'; i++) { if (i > 1 && s1[i - 1] == '-') { for (j--, k = s1[i - 2] + 1; k < s1[i]; k++) s2[j++] = k; } s2[j++] = s1[i]; } s2[j] = '\0'; } int main(void) { char s[] = "a-b-c-z012-9A-ZF-A-z?-"; char t[200]; expand(s, t); printf("[%s]\n", t); return 0; }