K&R 练习题 【每日一题】1-21

//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都要进行数组移动,时间复杂度比较高。 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值