2011-06-15 36 views
2

我想知道是否可以为我的代码获得一些帮助。我把一些部分代码如下如何使用putchar来“挤压”字符(Ansi-C)

/*reads char by char til EOF*/ 
while((c = getchar()) != EOF) 
{ 

    if(c == '\t') 
    { 
     putchar(' '); 
    } 
    else if(c == ' ') 
    { 
     putchar('d'); 
    } 
    else 
    { 
     putchar(c); 
    } 
} 

我现在要做的是挤压用户输入的空格字符。因此,如果用户将在:

一个[SPACE] [SPACE] [SPACE] [SPACE] [SPACE] [SPACE] [SPACE] [SPACE]一个

输出应该只是

a [空格] a

现在我已经设置了它,用于替换测试用途的所有空间。我将如何更改我的代码,以便打印出1个空格而不是用户放入的所有空格。

感谢您提前提供任何帮助。

回答

3

一个解决方案:

/*reads char by char til EOF*/ 
int hasspace = 0; 

while((c = getchar()) != EOF) 
{ 
    if (isspace(c)) 
     hasspace = 1; 
    } 
    else 
    { 
     if (hasspace) 
     { 
      hasspace = 0; 
      putchar(' '); 
     } 
     putchar(c); 
    }  
} 
+0

聪明,当您读取_last_空格字符时打印空间。我花了几次尝试阅读它才得到它。 :) – sarnold 2011-06-15 02:31:05

+0

当然,要求是不够的。输入是什么都是空白?一个空间,或没有? ;-) – 2011-06-15 02:38:43

4

只要保持一个空白标记:

int lastWasSpace = 0; 
while((c = getchar()) != EOF) { 
    if(c == '\t' || c == ' ') { // you could also use isspace() 
     if(!lastWasSpace) { 
      lastWasSpace = 1; 
      putchar(c); 
     } 
    } else { 
     lastWasSpace = 0; 
    } 
} 
+0

哈哈哈。你的解决方案和我做的不同的事情:你寻找空间(使用'isspace',而不是手动检查''''和''\ t''),而我的同一个角色的所有集群都挤在一个实例中。 :-) – 2011-06-15 02:12:58

+0

@Chris:他已经有了;我会添加评论。谢谢。 – Ryan 2011-06-15 02:16:10

1

记录,当你打印的空间,直到你找到另一封信中没有打印出来了。

使用你的代码为基础:

unsigned char space = 0; 

/* reads char by char until EOF */ 
while((c = getchar()) != EOF) 
{ 
    if(c == '\t') 
    { 
     putchar(' '); 
    } 
    else if(c == ' ') 
    { 
     /* state specific action */ 
     if(space == 0) { 
      putchar('d'); 
      space = 1; /* state transition */ 
     } 
    } 
    else 
    { 
     /* state transition */ 
     if(space == 1) { 
      space = 0; 
     } 

     putchar(c); 
    } 
} 

你去那里。一个非常非常简单的状态机。这很容易!第一

+0

每次迭代都不会将“空间”重置为“0”吗? – Ryan 2011-06-15 02:13:30

+0

嗯,我不确定..只需一分钟,我会测试。 – 2011-06-15 02:14:36

+0

@minitech它会的。我修好了,谢谢! – 2011-06-15 02:17:17

2
[email protected]:/tmp$ cat compress.c; echo 'this  is a test' | ./compress 
#include <stdio.h> 
int main() { 
int c, lastchar = 'x'; 
while ((c = getchar()) != EOF) { 
    if (c == '\t' || c == ' ') { 
    if (lastchar != ' ') { 
    putchar(' '); 
    lastchar = ' '; 
    } 
    } else { 
    putchar(c); 
    lastchar = c; 
    } 
} 
} 
this is a test 
+0

我想你的意思是'int c' :) – sarnold 2011-06-15 02:14:40

+0

谢谢,纠正。我猜只要文本没有任何0xff字符,它不会被注意到。 – 2011-06-15 02:56:18

2

第一件事,你怎么样声明c

while((c = getchar()) != EOF) 

如果cchar,那么就无法容纳所有文字一个EOF。确保c声明的数据类型大于char(通常为int)。

接下来,你可以处理一个把戏压缩多个空格:

int space_seen = 0; 

while((c = getchar()) != EOF) 
{ 

    if(c == '\t') 
    { 
     putchar(' '); 
    } 
    else if(c == ' ') 
    { 
     if (!space_seen) 
     { 
      putchar('d'); 
      space_seen = 1; 
     } 
    } 
    else 
    { 
     putchar(c); 
     space_seen = 0; 
    } 
} 

这招也是很好的跟踪解析字符串了。