1-21 编写程序 entab,将空格串替换为最少数量的制表符和空格,但要保持单词 之间的间隔不变

发布时间 2023-07-17 23:45:42作者: 语巫

Archlinux

GCC 13.1.1  20230429

2023-07-17 23:33:35 星期一

 


点击查看代码
#include<stdio.h>


#define tab_width 4     //制表符占4位


int main()
{
    int c_in, cnt, cnt_tmp, space_num, tab_num;

    c_in = cnt = cnt_tmp = space_num = tab_num = 0;

    while( (c_in=getchar()) != EOF )
    {
        if( c_in == ' ' ){
            cnt++;
        }
        if( c_in != ' ' ){
            cnt_tmp = cnt;
            cnt = 0;
            if( cnt_tmp >= 4 ){     //连续空格数小于4无须处理
                space_num = cnt_tmp % tab_width;
                tab_num = cnt_tmp / tab_width;
                while( space_num != 0 ){
                    space_num--;
                    printf("~");    //为结果清楚,改空格为'~' 
                }
                while( tab_num != 0 ){
                    tab_num--;
                    printf("||||");    //改制表符为'||||'
                }

            }

            putchar( c_in );    //非上述字符,直接输出
        }
    }

    return 0;
}


 


运行截图:

image

在“xdq”与“zs”之间输入6个空格,输出正确。

 


小白刚学习C语言,代码质量不高,欢迎评论。