I tend to approach these things by starting out with a reference
implementation and then step-by-step obscuring it. Here's a reference
implementation in C to get you going. If you prefer to hack in another
language and are too lazy, let me know and I'll write you one in your
language of choice.
#include <stdio.h>
int main(int argc, char **argv) {
int c,
last_char_whitespace = 1,
words = 0;
while ((c = getchar()) != EOF) {
switch (c) {
case ' ':
case '\n':
case '\t':
if (!last_char_whitespace)
++words;
last_char_whitespace = 1;
break;
default:
last_char_whitespace = 0;
}
}
printf("%d\n", words + !last_char_whitespace);
return 0;
}