fork(54) download
  1. #include <string.h>
  2. #include <stdio.h>
  3.  
  4. int words(const char sentence[ ])
  5. {
  6. int counted = 0; // result
  7.  
  8. // state:
  9. const char* it = sentence;
  10. int inword = 0;
  11.  
  12. do switch(*it) {
  13. case '\0':
  14. case ' ': case '\t': case '\n': case '\r': // TODO others?
  15. if (inword) { inword = 0; counted++; }
  16. break;
  17. default: inword = 1;
  18. } while(*it++);
  19.  
  20. return counted;
  21. }
  22.  
  23. int main(int argc, const char *argv[])
  24. {
  25. printf("%d\n", words(""));
  26. printf("%d\n", words("\t"));
  27. printf("%d\n", words(" a castle "));
  28. printf("%d\n", words("my world is a castle"));
  29. }
  30.  
  31.  
Runtime error #stdin #stdout 0.01s 1676KB
stdin
Standard input is empty
stdout
0
0
2
5