我已经开始学习 Dennis Ritchie 和 Brian W.Kernighan 合着的“The ANSI C Programming Language”。到目前为止,我只学习了getchar()、putchar()、while、for、if。有一个练习我必须只使用我现在学到的东西来做。以上是我唯一知道的。这是书中出现的练习:
练习 1-9。编写一个程序,将其输入复制到输出,将一个或多个空格的每个字符串替换为一个空格。
我知道 C#、Pascal、Objective-C 和一些 Java,但我不明白如何在不使用数组的情况下解决这个问题。我知道数组,但由于作者还没有介绍数组,所以我认为我不能使用它们。数组将在接下来的章节中教授。
最佳答案
实现 Nikolai 的解决方案,因为在代码中可能更容易理解,
#include <stdio.h>
#include <stdbool.h> /* C99, but a good idea to use nonetheless */
int main() {
bool was_space; /* state variable */
char c; /* one-character buffer */
while ( ( c = getchar() ) != EOF ) {
if ( ! was_space || c != ' ' ) putchar( c );
was_space = c == ' ';
}
return 0;
}
如果你真的想避免bool
,你可以使用int
。
关于c - ANSI C - 不使用数组替换空白字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10652374/