strtok() and strtok_r() functions in C with examples

C offer various strtok() and strtok r() methods for a string to be separated by a certain delimiter. Dividing a string is a simple task. We have a comma-separated number of stuff from a chart, for instance, but we want separate parts in an array.

Parameters

Str: This string’s values are changed and split into small strings.

delim: This is the boundary-containing string C. Those can vary from call to call.

Return Value

Its function returns a reference to the first token in the string that was identified. When there are no tokens remaining to retrieve, a null pointer is returned.

strtok()

Example:

The example below demonstrates the usage of the strtok() method.

Output:

strtok() and strtok_r() functions in C with examples

strtok_r()

Relevant to strtok() in C, strtok r() does the same job of decoding a string into a pattern for tokens. Strtok r() is a re-entered variant of strtok().

There are two ways we can call strtok_r()

Below is a simple C program displaying when to use strtok r():

Output:

strtok() and strtok_r() functions in C with examples

Another Example of strtok :

Output:

strtok() and strtok_r() functions in C with examples

Practical Application

Based on some extractors, strtok could be used to split a string into multiple strings. And use this feature, simple support for CSV files might be implemented. CSV files are delimited with commas.

Example:

Output:

strtok() and strtok_r() functions in C with examples

Pin It on Pinterest

Share This