A-Eのような表記を ABCDEに展開するプログラム

K&Rに出ていた問題を解いてみた.

static int expand(char *dest, const char *src)
{
    int i, j, dest_index;
    int length;
    char prev, next;

    length = strlen(src);

    dest_index = 0;
    for (i = 0; i < length; i++) {
        if (src[i] == '-' && (i != 0 && i != length - 1)) {
            prev = src[i - 1];
            next = src[i + 1];

            if (prev < next) {
                dest_index--;
                for (j = prev; j <= next; j++) {
                    dest[dest_index++] = j;
                }
                i += 1;
            } else {
                dest[dest_index++] = '-';
            }

        } else {
            dest[dest_index++] = src[i];
        }
    }

    dest[dest_index] = '\0';

    return 0;
}

テスト

int main (int argc, char *argv[])
{
    char dest[1024];

    expand(dest, "");
    ok(strcmp(dest, "") == 0);
    expand(dest, "a-z");
    ok(strcmp(dest, "abcdefghijklmnopqrstuvwxyz") == 0);
    expand(dest, "A-Z");
    ok(strcmp(dest, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == 0);
    expand(dest, "0-9");
    ok(strcmp(dest, "0123456789") == 0);
    expand(dest, "-0-9");
    ok(strcmp(dest, "-0123456789") == 0);
    expand(dest, "0-9-");
    ok(strcmp(dest, "0123456789-") == 0);
    expand(dest, "-0-9-");
    ok(strcmp(dest, "-0123456789-") == 0);
    expand(dest, "1-5A-E");
    ok(strcmp(dest, "12345ABCDE") == 0);
    expand(dest, "1-3-5");
    ok(strcmp(dest, "12345") == 0);

    return 0;
}

static void ok(int expr)
{
    static int test_num = 1;

    if (expr) {
        printf("%2d ok\n", test_num);
    } else {
        printf("%2d not ok\n", test_num);
    }

    test_num++;
}
 1 ok
 2 ok
 3 ok
 4 ok
 5 ok
 6 ok
 7 ok
 8 ok
 9 ok

そんなに深く考えずに書いたがテストを問題なく
パスしましたね。