strtok is a function of the standard library of the C programming language for finding tokens in a string. The sequence of function calls breaks the string into tokens , separated by delimiters.
Content
Function Prototype
The prototype described in the header file string.h :
char * strtok ( char * string , const char * delim );
string- a pointer to a string to be divided into tokens. After the call, the line changes. For a subsequent call, you can passNULL, then the function will continue to search in the original string.delimis a pointer to a string containing delimiters.
Return Value
The function returns a pointer to the first token found in the string. If no tokens are found, then a null pointer is returned.
Usage
Connection
- C
#include <string.h>
- C ++
#include <cstring>
Usage Example
#include <stdio.h>
#include <string.h>
int main ()
{
char str [] = "This is not a bug, this is a feature." ;
printf ( "Split the string \" % s \ " into tokens." , str );
char * pch = strtok ( str , ",." ); // in the second parameter, delimiters are specified (space, comma, period)
printf ( " \ n Tokens:" );
while ( pch ! = NULL ) // while there are tokens
{
printf ( " \ n % s" , pch );
pch = strtok ( NULL , ",." );
}
return 0 ;
}
Conclusion:
Split the line "This is not a bug, this is a feature." tokens. Tokens: it not bug this feature
Security
The strtok function strtok not reentrant . There are two thread-safe, non-standard functions - strtok_s (in VC ++) and strtok_r (in the POSIX standard).
Links
- C ++ reference: strtok (English) - description of strtok with an example.