#include #include #include char *dupstrfrag(const char *s, const char *t) { char *p = malloc(1 + t - s); if(p != NULL) { memcpy(p, s, t - s); p[t - s] = '\0'; } return p; } int count_tokens(const char *s, char c) { int count = 0; const char *p = s; while(p != NULL) { p = strchr(p, c); if(p != NULL) { while(*p == c) { ++p; } } ++count; } return count; } void split(char **tokens, int numtokens, const char *s, char c) { const char *p = s; const char *q = NULL; int token; for(token = 0; token < numtokens; token++) { q = strchr(p, c); if(q != NULL) { tokens[token] = dupstrfrag(p, q); p = q + 1; while(*p == c) { ++p; } } else { q = strchr(p, 0); tokens[token] = dupstrfrag(p, q); } } } void killtokenarray(char **t, int n) { int i; for(i = 0; i < n; i++) { free(t[n]); } free(t); } int main(void) { char test[] = "Now is the hour for all good men to come to the aid of their party."; char **tokens = NULL; int k; int i = count_tokens(test, ' '); tokens = malloc(i * sizeof *tokens); if(tokens != NULL) { split(tokens, i, test, ' '); for(k = 0; k < i; k++) { printf("[%s]\n", tokens[k]); } killtokenarray(tokens, i); } return 0; }