这是问题所在 例如
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);
}
我可以使用缩小尺寸的实现吗?
答案 0 :(得分:2)
假设您只删除' '
:
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 == ' '
替换为
答案 1 :(得分:0)
如果你不介意对“单词”的大小进行人为限制,那么很容易将它缩短一点:
// pick your limit here:
char word[256];
// and be sure the length here matches:
while (scanf("%255s", buffer))
printf(" %s", buffer);
答案 2 :(得分:0)
示例实施:
while ((c = getchar ()) != EOF)
{
putchar (c);
if (c == ' ')
{
while ((c = getchar ()) == ' ')
{}
if (c != EOF)
{
putchar (c);
}
}
}