C Library Function - strtok()
strtok() is a string-handling function in the C standard library, used to split a string into a series of substrings (i.e., "tokens").
C Library Function **char *strtok(char str, const char delim) Split a string str into a set of strings,delim as the delimiter.
Declaration
Below is the declaration of the strtok() function.
char *strtok(char *str, const char *delim)
Parameters
-
str: The string to be split. On the first call, pass the string to be split; on subsequent calls, pass
NULL, indicating that the same string continues to be split. -
delim: The delimiter string.
strtok()splits the string based on any one of the characters in this stringstr.
Return Value
Returns a pointer to the next token. If there are no more tokens, NULL is returned.
Example
The following example demonstrates the use of the strtok() function.
Example
#include
<
string.h
#include
<
stdio.h
int
main
(
)
{
char
str
[
80
]
=
"This is - www.runoob.com - website
"
;
const
char
s
[
2
]
=
"
"
;
char
token
;
/*
Get the first substring
*/
token
=
strtok
(
str
,
s
)
;
/*
Continue to get the other substrings
*/
while
(
token
!=
NULL
)
{
printf
(
"
%s
\
n
"
,
token
)
;
token
=
strtok
(
NULL
,
s
)
;
}
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
This is
www.runoob.com
website
Notes
-
Modify the original string:
strtok()modifies the passed string, replacing delimiters with\0(the null character). Therefore, the original string is destroyed. -
Not reentrant:
strtok()uses a static buffer to keep state, so it is not thread-safe. If used in a multithreaded environment, consider usingstrtok_r()(the reentrant version). -
Consecutive delimiters: If the string contains consecutive delimiters,
strtok()ignores them and returns the next valid token.
Reentrant version: strtok_r()
strtok_r() is the reentrant version of strtok(), allowing you to use it safely in a multithreaded environment. 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
#include
int
main
(
)
{
char
str
[
]
=
"This is a sample string"
;
char
token
;
char
saveptr
;
// First call to 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 be aware of its side effects (modifying the original string) and its non-reentrancy. In a multithreaded environment, it is recommended to use strtok_r() to avoid race conditions.
C Standard Library -