//write a program entab that replace strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. when either a tab or a single blank would suffice to reach a tab stop, which should be given preference?
//这个题要用最少数量的空格和tab来替代输入文本中的空格。
解:
#include <stdio.h>
#define MAX_BUFFER 1024 //定义一个线性表(数组)的最大容量。
#define SPACETOTAB 4 // 定义多少个space才能转化成\t。
int mgetline(char s[], int lim) //这个getline多次使用,应该背住,背住的前提是理解!
{
int c, i;
for(i = 0; i< lim -1 &&(c=getchar())!=EOF && c!= '\n'; i++)
s[i] = c;
if(c == '\n')
{
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
int main(void) //如果没有使用参数,最好写成void,和老版本的C兼容
{
int len, spaceLength = 0;
char line[MAX_BUFFER];
while(len = mgetline(line,MAX_BUFFER))
{
int i, t;
for(i = 0; i < len; i++)
{
if(line[i] == ' ')
spaceLength ++;
else
spaceLength = 0; //当不是空格的时候,一定要将spaceLength归零。
if(spaceLength == SPACETOTAB)
{
line[i-3] = '\t';
i = i-3;
len = len - 3;
for(t = i+1; t < len; t++)
line[t] = line[t+3];
spaceLength = 0; //转化完空格,一定将spaceLength归零
line[len] = '\0';//字符串结尾一定要注意\0
}
}
}
return 0;
}
http://users.powernet.co.uk/eton/kandr2/krx121.html 这个答案采用全局变量,其实思路差不多,但是这种方式并不是最优解,每次替代一个tab都要进行数组移动,时间复杂度比较高。