/** * * Implementation and example usage for string tokenization, * that is to say, splitting a string into pieces based * on a character. This implementation follows, not quite * perfectly, strtok in string.h * * @author gtowell * Created: Sep 2019 * Modified: Mar 2021 * **/ #include #include #ifndef NULL #define NULL (void *) 0 #endif /** * Used by strtok to hold the last place read from the target string * **/ char * mystrtok_lastp; /** * Tokenize a string. First call will return first part of string up to token * Note that this function modifies the passed string! * @param string the string to tokenize Should only be non-NULL on first call. * @param teh character to split up the string * @return a pointer to a part of the string * **/ char * mystrtok(char * string, char token) { if (string!=NULL) { mystrtok_lastp=string; } else { if (mystrtok_lastp==NULL) return NULL; mystrtok_lastp++; } char *holdp=mystrtok_lastp; char *nptr = mystrtok_lastp; while (*nptr!=token && *nptr!='\0') { nptr++; } if (*nptr=='\0') { mystrtok_lastp=NULL; } else { mystrtok_lastp=nptr; *nptr='\0'; } return holdp; } /** * Example of strtok usage. * Uses command line for input * cl1 should be a single character to split a string on e.g. , * cl2 should be the string to be split. e.g., "the,box,is,a,pen" * **/ int main(int argc, char *argv[]) { char splitter = argv[1][0]; char *string = argv[2]; char *splitPiece; printf("String \"%s\" is split into tokens using a single char \"%c\":\n", string, splitter); splitPiece = mystrtok(string, splitter); // get first token printf("%s\n", splitPiece); // get subsequent tokens -- NOTE USE OF NULL -- cannot split two string at same time while (NULL != (splitPiece = mystrtok(NULL, splitter))) { printf("%s\n", splitPiece); } }