我想知道我的代码能不能得到一些帮助。我在下面放了一些部分代码
/*reads char by char til EOF*/
while((c = getchar()) != EOF)
{
if(c == '\t')
{
putchar(' ');
}
else if(c == ' ')
{
putchar('d');
}
else
{
putchar(c);
}
}我现在要做的就是压缩用户输入的空格字符。因此,如果用户输入:
aSPACESPACESPACESPACEa
输出应该是
aSPACEa
现在我已经设置好了,为了测试的目的,它将所有的空格都替换为d。我如何改变我的代码,让它只打印出1个空格,而不是用户输入的所有空格。
提前感谢您的帮助。
发布于 2011-06-15 10:16:53
一种解决方案:
/*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);
}
}发布于 2011-06-15 10:11:59
只需保留一个空格标志:
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;
}
}发布于 2011-06-15 10:13:52
jcomeau@intrepid:/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 testhttps://stackoverflow.com/questions/6352222
复制相似问题