练习1-21 编写函数entab,将空格串替换为最少数量的制表符和空格,但要保持单词之间的间隔不变。
#include <stdio.h>
#define TAB_WIDTH (8)
int replace_tail_space_with_tab(char *buf, int n)
{
int i = n;
if (n != TAB_WIDTH || buf[n - 1] != ' ') {
return n;
}
while (--i >= 0) {
if (buf[i] != ' ') {
break;
}
}
buf[++i] = '\t';
return i + 1;
}
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
int c;
char buf[TAB_WIDTH];
int i = 0;
int n;
while((c = getchar()) != EOF) {
if (c == '\n' || c == '\t' || (i + 1) % TAB_WIDTH == 0) {
buf[i++] = c;
n = replace_tail_space_with_tab(buf, i);
for (int j = 0; j < n; j++) {
putchar(buf[j]);
}
i = 0;
}
else {
buf[i++] = c;
}
}
return 0;
}
运行结果:
标签:练习题,21,int,++,char,WIDTH,TAB,程序设计,buf From: https://blog.csdn.net/VincentKCSDN/article/details/142030403