`
josunghwa
  • 浏览: 3221 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

C程序设计语言(第二版·新版)练习 1-20,1-21

 
阅读更多

练习 1-20 编写程序 detab,将输入中的制表符替换成适当数目的空格,使空格充满到下一个制表符终止位的地方。假设制表符终止位的位置是固定的,比如每隔 n 列就会出现一个制表符终止位。n 应该作为变量还是符号常量呢?

 

练习 1-21 编写程序 entab,将空格串替换为最少数量的制表符和空格,但要保持单词之间的间隔不变。假设制表符终止位的位置与练习 1-20 的 detab 程序的情况相同。当使用一个制表符或者一个空格都可以到下一个制表符终止位时,选用哪一种替换字符比较好?

 

 

#include <stdio.h>

#define MAX_LEN 1000
#define TAB_LEN 8
#define SPACE  ' '

void detab(char from[], char to[]);
void entab(char from[], char to[]);

int main() {
	int c, len = 0;
	char str_tmp[MAX_LEN];
	char str_detab[MAX_LEN];
	char str_entab[MAX_LEN];

	while ((c = getchar()) != EOF) {
		str_tmp[len++] = c;
	}
	str_tmp[len] = '\0';

	detab(str_tmp, str_detab);
	printf("%s", str_detab);

	entab(str_detab, str_entab);
	printf("%s", str_entab);

	return 0;
}

void detab(char from[], char to[]) {
	int c;
	int len1 = 0;
	int len2 = 0;
	int line_len = 0;

	while ((c = from[len1++]) != EOF) {
		if (c == '\t') {
			int i, len;
			for (i = 0, len = TAB_LEN - line_len % TAB_LEN; i < len; ++i, ++line_len) {
				to[len2++] = ' ';
			}
		} else {
			to[len2++] = c;
			c == '\n' ? line_len = 0 : ++line_len;
		}
	}
}

void entab(char from[], char to[]) {
	int c;
	int len1 = 0;
	int len2 = 0;
	int line_len = 0;

	while ((c = from[len1]) != EOF) {
		to[len2] = c;
		if (line_len % TAB_LEN == TAB_LEN -1 && c == ' ') {
			int i, numOfSpace = 0;
			for (i = 1; i < TAB_LEN; i++) {
				if (to[len2 - i] == ' ') {
					++numOfSpace;
				} else {
					break;
				}
			}
			len2 -= numOfSpace;
			to[len2] = '\t';
		}
		len1++;
		len2++;
		c == '\n' ? line_len = 0 : ++line_len;
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics