#include <stdio.h>
#include <string.h>
int main ()
{
char str[50] ="Welcome-to-plus2net";
char *p;
p = strtok (str,"-");
printf ("%s\n",p);
}
Output is here
Welcome
Output of strtok() gives us a pointer to the first token. To get the subsequent tokens we have to use NULL in place of the main string.
We can parse a string into sequence of tokens by using strtok() string function.
strtok(main_string, delimiter_string);
#include <stdio.h>
#include <string.h>
int main ()
{
char str[50] ="Welcome-to-plus2net";
char *p;
p = strtok (str,"-");
printf ("%s\n",p); // Welcome
p = strtok(NULL,"-");
printf ("%s\n",p); // to
}
Output is here
Welcome
to
Note : In the second call to strtok() we have not used the original string, we used NULL
If no more tokens are found then we get NULL as output of strtok(). We will use this to loop through and display all tokens.
#include <stdio.h>
#include <string.h>
int main ()
{
char str[50] ="Welcome-to-plus2net";
char *p;
p = strtok (str,"-");
while( p != NULL ) {
printf( " %s\n", p );
p = strtok(NULL, "-");
}
}