typestar

Splitting with strtok in C

strtok cuts a string into tokens in place, which means it modifies the input.

#include <stdio.h>
#include <string.h>

int split_fields(char *line, const char *delims, char **out, int max) {
    int count = 0;
    char *token = strtok(line, delims);
    while (token != NULL && count < max) {
        out[count++] = token;
        token = strtok(NULL, delims);
    }
    return count;
}

void demo(void) {
    char line[] = "rust,104,97.5";
    char *fields[4];
    int n = split_fields(line, ",", fields, 4);
    for (int i = 0; i < n; i++) {
        printf("[%s]", fields[i]);
    }
    printf("\n");
}

How it works

  1. It writes NUL over each delimiter, so the buffer must be writable.
  2. The first call takes the string, later calls take NULL.
  3. It keeps hidden state, so it cannot be nested or shared.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
457
Tokens
154
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 92 seconds.

Type this snippet

Step 1 of 3 in Splitting & parsing, step 8 of 13 in Strings & text.

← Previous Next →