C 将输入复制到输出,对于包含一个或多个空格的字符串,输出一个空格
问题就在这里 比如说C 将输入复制到输出,对于包含一个或多个空格的字符串,输出一个空格,c,input,implementation,C,Input,Implementation,问题就在这里 比如说 in = "a b\nab c\ndd"; out = "a b\nb c\ndd" Here is my C code while(c=getchar()!=EOF){ if(c==' '){ while( (c1=getchar()) == ' '); // ignore all other contiguous blank putchar(c); // output one blank putchar(c1); //
in = "a b\nab c\ndd";
out = "a b\nb c\ndd"
Here is my C code
while(c=getchar()!=EOF){
if(c==' '){
while( (c1=getchar()) == ' '); // ignore all other contiguous blank
putchar(c); // output one blank
putchar(c1); // output the next non-blank character
}
else putchar(c);
}
我可以有一个缩小尺寸的实现吗 假设您只删除
”
:
int c;
char space_found = 0;
while ( ( c = getchar() ) != EOF) {
if ( (!space_found) || (c != ' ') ) { // if the previous is not a space, or this is not a space
putchar(c);
}
space_found = (c == ' '); // (un)set the flag
}
您可以通过一个简单的宏将其更改为检查任何空白:
#define is_white_space(X) ( ( (X) == ' ' ) || ( (X) == '\t' ) || ( (X) == '\n' ) )
并用它替换
c='
,如果你不介意人为地限制“单词”的大小,那么很容易将其缩短一点:
// pick your limit here:
char word[256];
// and be sure the length here matches:
while (scanf("%255s", buffer))
printf(" %s", buffer);
while ((c = getchar ()) != EOF)
{
putchar (c);
if (c == ' ')
{
while ((c = getchar ()) == ' ')
{}
if (c != EOF)
{
putchar (c);
}
}
}
在输出示例中,我认为您缺少第二行的
a
(因此应该是a b\nab c\ndd
)