Strtok_r in CIn this article, we will discuss the strtok_r() function in C with their syntax and examples. The two functions strtok() and strtok_r() in C allow us to divide a string by a delimiter. The task of splitting a string is quite frequent. For instance, we might desire individual things in an array from a comma-separated list of objects in a file. What is the strtok() Function?Str[] is divided using the specified delimiters by the strtok() method, which returns the subsequent token. It must be called repeatedly to obtain all tokens. When there are no more tokens, it returns NULL. Syntax of strtok():It has the following syntax: Parameters:str: It is the pointer to the string to be tokenized. delims: It is a string containing all delimiters. Return Value: It returns the pointer to the first token encountered in the string. It returns NULL if there are no more tokens found. Program: Let's take an example to split a string using the strtok() function in C. Output: What is strtok_r() Function?The Strtok_r() function performs the same task of parsing a string into a sequence of tokens as the strtok() function in C. As a reentrant variant of strtok(), strtok_r() is thread safe. Syntax of strtok_r():It has the following syntax: Parameters:str: It is the pointer to the string to be tokenized. delims: It is a string containing all delimiters. saveptr: It is a pointer to a char * variable that is used internally by strtok_r() to maintain context between successive calls that parse the same string. Return Value: It returns the pointer to the first token encountered in the string. It returns NULL if there are no more tokens found. Program:Let's take an example to split a string using the strtok_r() function in C. Output: Difference Between strtok() and strtok_r()There are several differences between the strtok() and strtok_r() in C. Some main difference between the strtok() and strtok_r() in C are as follows:
Benefits of strtok_r()A string can be tokenized (divided) into smaller substrings using the strtok_r() method, which is a version of the strtok() function in C and C++. Strtok_r() is thread-safe and reentrant, making it a safer option in multithreaded or reentrant applications. The main distinction between strtok() and strtok_r() is that strtok_r() is thread-safe and reentrant. The advantages of using strtok_r() are as follows:
Conclusion:In conclusion, strtok_r() is a more secure and flexible substitute for strtok() for tokenizing strings in a multithreaded or reentrant context. In these situations, its explicit saveptr parameter and thread safety make it the best option. Next TopicC Programming Test |