In the C programming language, strtok_r is a function used for splitting strings and serves as the thread-safe variant of strtok. This means that strtok_r can be safely used in multi-threaded programs, whereas strtok may cause issues because it relies on static storage to store the remaining string from the previous call.
strtok_r Function Prototype:
cchar *strtok_r(char *str, const char *delim, char **saveptr);
- str: The original string to be split; in the first call, it points to the string to be split, and in subsequent calls, it must be set to NULL.
- delim: A string containing delimiters used to split the original string.
- saveptr: Used to store the position of the remaining string for the next function call.
Usage Example:
Suppose we have a task to split a line of text where words are separated by spaces.
c#include <stdio.h> #include <string.h> int main() { char input[] = "Hello world this is an example"; char *token; char *rest = input; while ((token = strtok_r(rest, " ", &rest))) { printf("Token: %s\n", token); } return 0; }
In this example:
- The
inputstring contains the original text to be split. - We obtain each word (with space as the delimiter) step by step using
strtok_rwithin a while loop. - The first parameter is the string to be split (
input) in the initial call; for subsequent calls to retrieve remaining substrings, it is set to NULL. - The
delimparameter is a string containing a single space character, representing the delimiter. - The
saveptrparameter stores the position of the remaining string during the call for the next invocation.
Important Notes:
- Use
strtok_rinstead ofstrtokin multi-threaded environments to avoid race conditions and other thread-safety issues. - After using
strtok_rto split the string, the originalinputstring is modified becausestrtok_rinserts '\0' at each delimiter.
Through this example and explanation, you can see how strtok_r is used in actual programs to safely split strings, especially when thread safety is required.
2024年6月29日 12:07 回复