C library functions -strtok()

C Standard Library - <string.h>

strtok() is a string processing function in the C standard library, used to split a string into a series of substrings (i.e., "tokens").

C Library Functionschar *strtok(char *str, const char *delim)Split stringstrFor a set of strings,delimas the delimiter.

Declaration

Below is the declaration of the strtok() function.

char *strtok(char *str, const char *delim)

Parameter

  • str: The string to be split. On the first call, pass the string to be split; on subsequent calls, passNULL, indicating to continue splitting the same string.

  • delim: The delimiter string.strtok()will split based on any character in this string.str。

Return Value

Returns a pointer to the next token. If there are no more tokens, returns NULL.

Example

The following example demonstrates the usage of the strtok() function.

Example

#include <string.h> #include <stdio.h> int main () { char str[80] = "This is - www.example.com - website"; const char s[2] = "-"; char *token; /*Get the first substring*/ token = strtok(str, s); /*Continue to get the remaining substrings*/ while( token != NULL ) { printf( "%s\n", token ); token = strtok(NULL, s); } return(0); }

Let us compile and run the above program, which will produce the following result:

This is 
 www.example.com 
 website

Notes

  1. Modify the original string: strtok()will modify the passed-in string, replacing the delimiters with\0(null character). Therefore, the original string will be destroyed.

  2. Non-reentrant: strtok()It uses a static buffer to save state, so it is not thread-safe. If used in a multi-threaded environment, consider usingstrtok_r()(reentrant version).

  3. Consecutive delimiters: If there are consecutive delimiters in the string,strtok()it will ignore them and return the next valid token.


Reentrant version: strtok_r()

strtok_r() is a reentrant version of strtok(), which allows you to use it safely in multi-threaded environments. Its prototype is as follows:

char *strtok_r(char *str, const char *delim, char **saveptr);

saveptr: is a pointer to char*, used to save the splitting state.

Example

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "This is a sample string";
    char *token;
    char *saveptr;

    // First call strtok_r, passing the string to be split
    token = strtok_r(str, " ", &saveptr);

    // Continue calling strtok_r until it returns NULL
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok_r(NULL, " ", &saveptr);
    }

    return 0;
}

strtok() is a convenient string splitting function, but you need to be aware of its side effects (modifying the original string) and non-reentrancy. In multi-threaded environments, it is recommended to use strtok_r() to avoid race conditions.

C Standard Library - <string.h>

other extensions