#include <string.h>
#include <stdio.h>
int words(const char sentence[ ])
{
int counted = 0; // result
// state:
const char* it = sentence;
int inword = 0;
do switch(*it) {
case '\0':
case ' ': case '\t': case '\n': case '\r': // TODO others?
if (inword) { inword = 0; counted++; }
break;
default: inword = 1;
} while(*it++);
return counted;
}
int main(int argc, const char *argv[])
{
printf("%d\n", words
(" a castle ")); printf("%d\n", words
("my world is a castle")); }
I2luY2x1ZGUgPHN0cmluZy5oPgojaW5jbHVkZSA8c3RkaW8uaD4KCmludCB3b3Jkcyhjb25zdCBjaGFyIHNlbnRlbmNlWyBdKQp7CiAgICBpbnQgY291bnRlZCA9IDA7IC8vIHJlc3VsdAoKICAgIC8vIHN0YXRlOgogICAgY29uc3QgY2hhciogaXQgPSBzZW50ZW5jZTsKICAgIGludCBpbndvcmQgPSAwOwoKICAgIGRvIHN3aXRjaCgqaXQpIHsKICAgICAgICBjYXNlICdcMCc6IAogICAgICAgIGNhc2UgJyAnOiBjYXNlICdcdCc6IGNhc2UgJ1xuJzogY2FzZSAnXHInOiAvLyBUT0RPIG90aGVycz8KICAgICAgICAgICAgaWYgKGlud29yZCkgeyBpbndvcmQgPSAwOyBjb3VudGVkKys7IH0KICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgZGVmYXVsdDogaW53b3JkID0gMTsKICAgIH0gd2hpbGUoKml0KyspOwoKICAgIHJldHVybiBjb3VudGVkOwp9CgppbnQgbWFpbihpbnQgYXJnYywgY29uc3QgY2hhciAqYXJndltdKQp7CiAgICBwcmludGYoIiVkXG4iLCB3b3JkcygiIikpOwogICAgcHJpbnRmKCIlZFxuIiwgd29yZHMoIlx0IikpOwogICAgcHJpbnRmKCIlZFxuIiwgd29yZHMoIiAgIGEgICAgICBjYXN0bGUgICAgICIpKTsKICAgIHByaW50ZigiJWRcbiIsIHdvcmRzKCJteSB3b3JsZCBpcyBhIGNhc3RsZSIpKTsKfQoK