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 finds
1char str[] = "apple,banana,cherry,date";
// The set of delimiter characters, here just a comma
2char *delim = ",";
// Will point to each token in turn
3char *token;
// Number of tokens found so far
4int 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 left
7while (token != NULL) {
// Counts this token
8 count++;
// Prints Token 1: apple through Token 4: date
9 printf("Token %d: %s\n", count, token);
// Passing NULL continues from where the previous call stopped
10 token = strtok(NULL, delim);
11}
12
// Prints Total tokens: 4
13printf("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

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

More C examples at level 5

← C typing practice