strtok(): parse string into tokens

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);
}
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.
#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, "-");
   }
}
Output is here
Welcome
to
plus2net
Your Rating




Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer