×

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

Doubly Linked list in C

To know the Doubly Linked List in C, first we should know about how the Linked List works. Linked List The Linked list is the linear data structure. In the Linked...

5 minutes read.

How to delete a file in C

A file is a group of data kept on a secondary device, such as a hard disc. It is typically utilized as a real-world application with a lot of data. These...

3 minutes read.

How to use floor() function in C

Introduction: The floor() used as a function in the C programming language. This function uses to return the largest or most significant integer value. The integer value is smaller than...

3 minutes read.

Storage class in C

Storage class in C defines the scope, the visibility, and the lifetime of variables and functions. In other words, storage classes are used to describe the features of variables and...

3 minutes read.

Fahrenheit to Celsius in C

Before going into conversion, we have to know what Fahrenheit and Celsius mean, these are both units to measure the temperature.In our daily life, we use both Fahrenheit and Celsius,...

1 minute read.

Actual and Formal Parameters

Any variable declared within the parenthesis is referred to as the parameters during the function declaration. Parameters tell the function about the argument datatype, their order, and the number of...

5 minutes read.

Static in C

Static is a keyword that is used in the C programming language. It can be used both as variables and as functions. In other words, it can be declared both...

3 minutes read.

Cbrt() function in C

Introduction: The Cbrt is a function used in C programming language. The cbrt() function is a math function. Using the cbrt function, we can do the cube root of a function. This...

4 minutes read.

Error handling in C

Error handling in C: The C programming standard does not provide direct convenience for handling the errors. However, being a system programming language, it definitely will give access to handling...

4 minutes read.

String Handling functions in C

String :- The String is the collection of characters. Every String ends with the null character, and the String is enclosed in the double quotations .ie, "javaTpoint". If we see any...

5 minutes read.

Self-referential structure in C

Self-referential structure in C A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers...

3 minutes read.

Flow chart of While loop in C

This is a flowchart that represents the process of executing the while loop in the C programming language.Generally, as we know there are three main components of while loop:1. The...

3 minutes read.

What are linker and loader in C

Linker and loader are utility programs that have a significant role in executing a program. Linker: A linker is a program that joins the object files produced by the assembler/ compiler...

3 minutes read.

Merge Sort in C

The merge sort follows the principle of the divide and conquers algorithm. Firstly it divides the input of an array into two halves and then calls itself for the two...

4 minutes 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.

Matrix Multiplication in C

Matrix Multiplication in C Matrix multiplication in C: Two matrices can be added, subtracted, multiplied, and divided. To do so, we take input from the consumer for row number, column number, first element matrix,...

3 minutes read.

Factorial Program in C using For Loop

Before move on the factorial program. We have to know about the for loop in C programming language. The syntax of the For Loop is: for (initialization statement; test expression; an increment...

3 minutes read.

Pure Virtual Function in C

Before knowing about the pure virtual function some of the important points about the virtual function in C++ are given below. In c++ the member function that is defined in the...

4 minutes read.

C/C++ Program to Find the Size of int, float, double and char

In this tutorial, we will learn how to use the sizeof operator to determine the size of each variable. Program to Determine Variable Size Write a C or C++ program to determine the...

2 minutes read.

Write() function in c

As the name suggests the write () function is used to write the file descriptor. In other words it is used to write any file name without specifying file name,...

3 minutes read.