- 论坛徽章:
- 0
|
原题是说用最少的TAB和空格来替换空格串,但要保持单词间的距离。
习题解答给出的答案如下:
#include <stdio.h>
#define TABINC 8
main()
{
int c, nb, nt, pos;
nb = 0;
nt = 0;
for (pos = 1; (c = getchar()) != EOF; ++pos)
if (c == ' ') {
if (pos % TABINC != 0)
++nb;
else {
nb = 0;
++nt;
}
} else {
for ( ; nt > 0; -- nt)
putchar('\t');
if (c == '\t')
nb = 0;
else
for ( ; nb > 0; --nb)
putchar(' ');
putchar(c);
if (c == '\n')
pos = 0;
else if (c == '\t')
pos = pos + (TABINC - (pos-1) % TABINC) -1;
}
} |
感觉和我想的出入很大,特别是这里:
for (pos = 1; (c = getchar()) != EOF; ++pos)
if (c == ' ') {
if (pos % TABINC != 0)
++nb;
else {
nb = 0;
++nt;
用pos的位置MOD TABINC(8)来确定TAB的数量,如果是这样的一个串"aaa a",即3个非空格,5个空格,1个非空格。那么在pos到达最后一个空格时pos = 8, 按这个算法将得到 pos % TABINC = 0, 于是用一个'\t'来替换所有空格,可此处只有5个空格,达不到8个空格的TAB要求啊?这样替换后不是不能保持单词间的距离了么?
是我想错了,还是哪里没有理解清楚?
希望大家帮忙。
[ 本帖最后由 niexinnm 于 2008-9-9 18:17 编辑 ] |
|