Scripting languages like Php, Python and Perl provide some nice tools to "explode" a string into various elements or tokens. We will need this too in our first project and it provides a nice opportunity for creating a bunch of little string objects out of a larger object. Here is most of the code. newLine is from the previous example.
#include <stdio.h> #include <stdlib.h> /* Skip over whitespace to find non-space character returns: pointer to first non-space char or NULL if none present */ char *startWord(char *p) { while (isspace(*p)) p++; if (*p == '\0') return NULL; return p; } /* Return pointer to first space char or terminator */ char *endWord(char *p) { while ((*p != '\0') && !isspace(*p)) p++; return p; } /* Return a string consisting of the word in [start,end) */ #define MAXWORD 128 char *newWord(char *start, char *end) { char *w; ... you write this part ... w = (char *) malloc( ... ); ... return w; } ... int main(int argc, char *argv[]) { char *s; FILE *infile; FILE *ofile; char *strt, *end, *word; infile = stdin; ofile = stdout; if (argc >= 3) ofile = fopen(argv[2],"w"); if (argc >= 2) infile = fopen(argv[1],"r"); s = newLine(infile); while (s) { strt = startWord(s); while (strt) { end = endWord(strt); word = newWord(strt,end); fprintf(ofile,"%s ",word); strt = startWord(end); } fprintf(ofile,"\n"); s = newLine(infile); } fclose(ofile); return 0; }It should print out all the "words" that you counted before.