w3resource

C - strtok() function

C strtok() function - Split string into tokens

Syntax:

char *strtok(char *strToken, const char *strDelimit)

The strtok() function is used to read string1 as a series of zero or more tokens, and string2 as the set of characters serving as delimiters of the tokens in string1.
The tokens in string1 can be separated by one or more of the delimiters from string2. The tokens in string1 can be located by a series of calls to the strtok() function.

Parameters:

Name Description Required /Optional
strToken String containing token or tokens. Required
strDelimit Set of delimiter characters. Required

Return value from strtok()

  • Upon successful completion, strtok() shall return a pointer to the first byte of a token.
  • Otherwise, if there is no token, strtok() shall return a null pointer.

Example: strtok() function


#include <string.h>
#include <stdio.h>

char string[] = "C Programming\t ,,Exercises\nand Solution";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf("Original string: C Programming\\t ,,Exercises\\nand Solution");
    printf("\nSeparators: ,\\t\\n");
	printf( "\n\nTokens of the original string:\n" );

    token = strtok( string, seps );
    while( token != NULL )
    {
      // While there are tokens in "string"
      printf( "%s\n", token );

      // Get next token:
      token = strtok( NULL, seps );
    }
}

Output:

Original string: C Programming\t ,,Exercises\nand Solution
Separators: ,\t\n

Tokens of the original string:
C
Programming
Exercises
and
Solution

C Programming Code Editor:

Previous C Programming: C strstr()
Next C Programming: C strxfrm()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/string/c-strtok.php