×

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

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.

#include <string.h>
#include <stdio.h>
int main () {
   char str[80] = "Hello - www.Tutorialandexample.com";
   const char k[2] = "-";
   char *token;
   token = strtok(str, k);
   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token );
      token = strtok(NULL, k);
   }
   return(0);
}

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()

A third saveptr argument is a char-pointer *
Variable which strtok r() uses internally in
Keep context between subsequent calls
Parse that same string.
Char * strtok r(char * str, * delim, char * * saveptr) const char;

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

// C program to demonstrate working of strtok_r()
// by splitting string based on space character.
#include <stdio.h>
#include <string.h>
int main()
{
    char str[] = "Tutorial and example";
    char* token;
    char* rest = str;
    while ((token = strtok_r(rest, " ", &rest)))
        printf("%s\n", token);
    return (0);
}

Output:

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

Another Example of strtok :

// C code to demonstrate working of
// strtok
#include <stdio.h>
#include <string.h>
// Driver function
int main()
{
          // Declaration of string
          char gfg[100] = " Tutorial - and - example -";
          // Declaration of delimiter
          const char k[4] = "-";
          char* tok;
          // Use of strtok
          // get first token
          tok = strtok(gfg, k);
          // Checks for delimeter
          while (tok != 0) {
                   printf(" %s\n", tok);
                   // Use of strtok
                   // go through other tokens
                   tok = strtok(0, k);
          }
          return (0);
}

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:

// C code to demonstrate the practical application of
#include <stdio.h>
#include <string.h>
// Driver function
int main()
{
          char gfg[100] = " 1998 Ford E370 AC 3000.";
          const char k[4] = " ";
          char* tok;
          tok = strtok(gfg, k);
          while (tok != 0) {
                   printf("%s, ", tok);
                   tok = strtok(0, k);
          }
          return (0);
}

Output:

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

Related Topics

Recursion in C

Recursion is a programming technique that allows the programmer to call the function within the same function. The function which calls the same function is known as recursive function but a...

1 minute read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

C and C++ Binary Files

What is a binary file? A file in which the content is written in binary format is called a binary file. A binary file is not a text file. There are...

7 minutes read.

Variable in C

Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of...

2 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

Inline Function in C

Inline Function in C A normal function will become an inline function when the function prototype of that function is prepended with the keyword "inline". Inline functions are the function where...

4 minutes read.

memmove() in C

Introduction: In this article we are discuss about the memmove() function in C. This function transfers memory blocks from one location to another. The memmove() function is declared in the...

3 minutes read.

C Math Library

C Math Library The <math.h> header defines various mathematical functions and one macro. Many functions are available in this library to take double as an argument and then return double as...

4 minutes read.

Nested Structure in C

In C language, we can create nested Structure (Structure within Structure). There are two ways to define a nested structure. By separate structure By Embedded structure   Separate structure In a separate...

1 minute read.

Multiplication table program in C using For loop

Before we move on the program of multiplication table of any natural number, first we have to know about the For loop statement. The syntax of ‘for’ loop in C programming...

3 minutes read.

Scope of variables in C

Introduction The scope of variables in C can be defined as the scope of reach of a variable, the term scope is used to determine the visible range of an object....

4 minutes read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

C Program for Extended Euclidean algorithms

The Euclidean method simply computes the GCD (greatest common divisor) of two numbers, p and q. (Let's assume) The GCD of two integers is the greatest number that divides them both....

3 minutes read.

Conio.h in C

Header files are the source files with the extension of .h. In c language header files are referred to as the helping files and they contain definitions of various functions...

4 minutes read.

Remove an element from an array in C

A collection of objects or pieces of the same data type stored in a single memory block is known as an array. A data structure called an array is used...

3 minutes read.

Flexible Array Members in a Structure in C

There is flexibility to declare array from c99 generation onwards that declaration of the collections can be made possible without even mentioning its dimension, which means that the displays are...

4 minutes read.

Bigint (BIG INTEGERS) in C with Example

The maximum number of digits that a long, long int can have in C/C++ is 20. The issue is how to store the 22-digit number, which is difficult to do...

9 minutes read.

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

Bank Account System in C using File Handling

This tells about the creation of bank account system using the C language and handling of files in C. Approach Let us see the approaches and the functions how they are covering...

5 minutes read.