C 习题 entab函数实现

2019-03-30  本文已影响0人  吃柠檬的鸮

习题1 - 21 编写程序 entab,将空格串替换为最少数量的制表符和空格,但要保持单词直接的间隔不变。假设制表符终止位的位置是固定的。当使用一个制表符或者一个空格都可以到达下一个制表符终止位时,选用哪一种替换字符比较好?

完整代码清单如下:

/* ex21.c */
#include <stdio.h>

#define TAB     8
#define LIMIT   1000

int getLine(char line[], int limit) {
    int i = 0;
    int c;

    if ((c = getchar()) == EOF) {
        return 0;
    }
    
    while (c != '\n') {
        line[i++] = c;
        c = getchar();
    }
    line[i++] = '\0';

    return i;
}

void entab(char line[]) {
    int i = 0;
    int space = 0;
    int output = 0;
    int delete;

    while (line[i] != '\0') {
        if (line[i] == ' ') {
            ++space;
            ++i;
        } else {
            if (space) {
                while ((output % TAB + space) > TAB) {
                    putchar('\t');
                    delete = (TAB - output % TAB);
                    output += delete;
                    space -= delete;
                }
                while (space) {
                    putchar(' ');
                    --space;
                    ++output;
                }
            }
            putchar(line[i++]);
            ++output;
        }
    }
    putchar('\n');
}

int main() {
    char line[LIMIT];

    while (getLine(line, LIMIT) > 0) {
        entab(line);
    }

    return 0;
}

编译运行结果:

$ ./ex21.out
123      123
123  123
12   12      123          123
12   12      123      123
$
上一篇 下一篇

猜你喜欢

热点阅读