Related functions: Index, memchr, rindex, strpbrk, strsep, strspn, strstr
Header file: The split function in # include <string. h> C/C ++ is strtok (). Its function prototype is as follows:
Char * strtok (char * STR, const char * delimiters );
Function Description
Strtok () is used to split strings into segments. The STR parameter points to the string to be split, and the delimiters parameter is the split string. When strtok () when the delimiters Delimiter is found in the STR string, the Delimiter is changed to '\ 0. In the first call, strtok () must be given the STR string parameter. In future calls, the STR parameter is set to null. If each call is successful, the next split string pointer is returned.
Return Value
Returns the string pointer after the next split. If no split exists, null is returned.
Example-1
/* Strtok example */
# Include <stdio. h>
# Include <string. h>
Int main ()
{
Char STR [] = "A, B, C, D * E ";
Const char * Split = ",";
Char * P;
P = strtok (STR, split );
While (P! = NULL ){
Printf ("% s \ n", P );
P = strtok (null, split );
}
Getchar ();
Return 0;
}
In this example, the strings 'a, B, c, d * E "are separated by commas (,) as delimiters.
The output result is as follows:
A
B
C
D * E
Because delimiters supports multiple delimiters, we use the statement lines in this example.
Const char * Split = ",";
Change to const char * Split = ", *"; // use commas (,) and asterisk (*) to separate strings.
The output result is as follows:
A
B
C
D
E Example 2: # include <string. h>
# Include <stdio. h>
# Include <stdlib. h>
Char string [] = "1: IP: ipport: User ";
Char SEPs [] = ":";
Char * token;
Int main (void)
{
Printf ("tokens: \ n ");
// Establish string and get the first token:
Token = strtok (string, SEPs); // c4996
// Note: strtok is deprecated; Consider using strtok_s instead
While (Token! = NULL)
{
// While there are tokens in "string"
Printf ("% s \ n", token );
// Get next token:
Token = strtok (null, SEPs); // c4996
}
System ("pause ");
Return 0;
}