Finding a next token in a string using strtok() C function
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows 2003 Server Standard Edition
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info:
To do: Finding a next token in the given string using strtok() C function
To show: How to use strtok()/strtok_s() C function to find a next token in a string
// In this program, a loop uses strtok_s(), a secure version of the strtok() to print all the tokens (separated by commas or blanks) in two strings at the same time
// Other version wcstok() - wide character/unicode, _mbstok() - multibyte
#include <string.h>
#include <stdio.h>
// Global variables
char string1[] = "A string\tof ,,tokens\nand some more tokens";
char string2[] = "Another string\n\tparsed at the same time.";
char seps[] = " ,\t\n";
char *token1,
*token2,
*next_token1,
*next_token2;
int main(void)
{
printf( "Tokens:\n" );
// Establish string and get the first token:
token1 = strtok_s( string1, seps, &next_token1);
token2 = strtok_s ( string2, seps, &next_token2);
// While there are tokens in "string1" or "string2"
while ((token1 != NULL) || (token2 != NULL))
{
// Get next token:
if (token1 != NULL)
{
printf( " %s\n", token1 );
token1 = strtok_s( NULL, seps, &next_token1);
}
if (token2 != NULL)
{
printf(" %s\n", token2 );
token2 = strtok_s (NULL, seps, &next_token2);
}
}
}
Output example:
Tokens:
A
Another
string
string
of
parsed
tokens
at
and
the
some
same
more
time.
tokens
Press any key to continue . . .