strtok in C: solved exercise for splitting CSV strings

strtok in C: solved exercise for splitting CSV strings

If you are looking for strtok in c: solved exercise for splitting csv strings, here is a practical, compilable example focused on the reusable idea behind the exercise.

Problem statement

Split rojo,verde,azul into comma-separated tokens and print them one per line.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <stdio.h>
#include <string.h>

int main(void) {
    char linea[] = "rojo,verde,azul";
    char *token = strtok(linea, ",");

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, ",");
    }

    return 0;
}

Expected output

1
2
3
rojo
verde
azul

Common mistakes

  • Not testing edge cases such as small or empty inputs.
  • Not validating indices, pointers, or limits carefully enough.
  • Copying the mechanics without understanding the general pattern.

Practical use

This pattern appears frequently in text handling, input validation, and buffer manipulation.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful in practice?

Yes. It is designed to teach a reusable C pattern rather than a one-off toy example.

How should I practice it better?

Change the input data, add edge cases, and rewrite it from scratch without looking at the solution.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.