[C language:]将空格串替换为最小数量的制表符和空格,但要保持单词之间的间隔不变。

#include <stdio.h>
#define NSPACE  8
int main(int argc, char *argv[])
{
    int cspace;//count of blank space
    int c;
    int npos=1;//position of character in line
    cspace=0;
    while((c=getchar())!=EOF)
    {
        npos++;
        if(c==' ')
        {
            cspace++;
        }
        else
        {
            int i;
            if(cspace>0)//It found that some blank space is not processed
            {

                int nb=NSPACE-(npos-cspace-1)%NSPACE;//the number of blank that a TAB  equivalently in the position of start-blank
                if(nb<cspace)
                {

                    putchar('\t');
                    int nt=(cspace-nb)/NSPACE;
                    for(i=0; i<nt; i++)
                    {
                        putchar('\t');
                    }
                    int ns=(cspace-nb)%NSPACE;
                    for(i=0; i<ns; i++)
                    {
                        putchar(' ');
                    }
                }
                else
                {
                    for(i=0; i<cspace; i++)
                    {
                        putchar(' ');
                    }
                }
            }
            putchar(c);
            cspace=0;
        }
    }
    return 0;
}

  

posted @ 2012-03-09 00:30  flyice  阅读(412)  评论(0)    收藏  举报