============================================================================ Faculty of Applied Science and Engineering, University of Toronto CSC181: Introduction to Computer Programming, Fall 2000 Tutorial Notes, Week 9 ============================================================================ ----------------- Summary of Topics ----------------- - String Processing ------------ Introduction ------------ String processing is usually done with pointers. This is partly because many of the string library functions take pointers as arguments and have pointers as return values. Refer to King, Ch. 13 for more details. --------------------------------- Example: Removing trailing blanks --------------------------------- void removeLeadingBlanks(char *s) { char* t; for (t = s; *t != '\0' && *t == ' '; t++) ; strcpy(s, t); } ----------------------------------------------- Example: Printing all of the tokens in a string ----------------------------------------------- We want to print all of the tokens in a string, which are separated by a delimiting character (such as a space or a comma). For example, if we process " the quick brown fox ", then "the", "quick", "brown" and "fox" should be printed. Note that leading and trailing spces, as well as runs of consecutive spaces don't appear in the printed words. void split(const char* s, const char c) { const char* start; const char* end; start = s; end = strchr(start, c); while (end != NULL) { if (start != end) { char *token; token = malloc(end-start+1); token[end-start] = '\0'; strncpy(token, start, end-start); printf("%s\n", token); free(token); } start = end + 1; end = strchr(start, c); } if (strlen(start) > 0) { printf("%s\n", start); } }