The C ++ programming language is flexible and supports various programming styles. Here we will introduce how to use C ++ strtok () to implement the functions of the Split function. We hope you can experience the power of this language.
- Summary of C ++ multi-thread testing
- Detailed description of the C ++ explicit keyword Application Method
- C ++ function Overloading is implemented through C Language
- Questions about C ++ polymorphism coverage
- Overview of C ++ streaming File Operations
Related functions: index, memchr, rindex, strpbrk, strsep, strspn, strstr
Header file: # include <string. h>
The Split function in C/C ++ is C ++ strtok (). Its prototype is as follows:
- char * strtok (char * str, const char * delimiters);
Function Description
C ++ 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
- 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;
- }
The preceding section describes C ++ strtok.