String Tokenization in C
Level 5258 keystrokes
Splits "apple,banana,cherry,date" at commas with strtok: the first call receives the string and later calls pass NULL to continue. It prints the four tokens with their numbers and then Total tokens: 4.
C code
// Must be a modifiable array: strtok writes '\0' over each delimiter it finds1char str[] = "apple,banana,cherry,date";// The set of delimiter characters, here just a comma2char *delim = ",";// Will point to each token in turn3char *token;// Number of tokens found so far4int count = 0;5 // The first call passes the string and returns the first token, "apple"6token = strtok(str, delim);// strtok returns NULL when no tokens are left7while (token != NULL) { // Counts this token8 count++; // Prints Token 1: apple through Token 4: date9 printf("Token %d: %s\n", count, token); // Passing NULL continues from where the previous call stopped10 token = strtok(NULL, delim);11}12 // Prints Total tokens: 413printf("Total tokens: %d\n", count);Output
Token 1: apple Token 2: banana Token 3: cherry Token 4: date Total tokens: 4
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
,× 9;× 9"× 8=× 6(× 5)× 5%× 3:× 2*× 2\× 2