Ad space (banner)
๐Ÿ”งC Lessons
Lesson 20 / 68

Splitting Strings (strtok)

This lesson covers splitting a string in C with strtok, so you can work with data like CSV. It's for anyone searching "C strtok usage."

strtok() is a function for splitting a string on a given delimiter. C has no dedicated split method, so using this function is the traditional approach.

The example gets the first token with strtok(csv, ","), then repeatedly calls strtok(NULL, ",") inside a while loop to get the remaining tokens one at a time. Notice the distinctive usage of passing NULL as the first argument from the second call onward.

A common early mistake is not realizing strtok() directly modifies the original string. It inserts a terminating character at each delimiter's position, so you need to keep a copy if you want to use the original string later.

In real projects, splitting a string is a frequent need in real business systems too โ€” reading a CSV file or parsing a log line, for example.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)