Share on Google+Share on Google+

C String Tokenizer

Advertisement
In this section, you will learn how to use strtok() function to break the string into a series of tokens.

C String Tokenizer

     

In this section, you will learn how to use strtok() function to break the string into a series of tokens. You can see in the given example, we have define a string and a pointer. The expression ch = strtok (st," ") extract the string from the string sequence one by one and printf ("%s\n", ch) prints the string after being tokenized. The expression ch = strtok (NULL, " ,") extract the whole string from the string sequence till the ch get equal to null.

Here is the code:

 

 

 

 

TOKENIZE.C

#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
  char st[] ="Where there is will, there is a way.";
  char *ch;
  clrscr();
  printf("Split \"%s\"\n", st);
  ch = strtok(st, " ");
  while (ch != NULL) {
  printf("%s\n", ch);
  ch = strtok(NULL, " ,");
  }
  getch();
  return 0;
}

Output will be displayed as:

TOKENIZE.EXE

Download Source Code:

Advertisements

Posted on: February 6, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Comments:2
noureen
December 16, 2011
c tokenizer

how to use tokenizers in different ways as one of the way for eg: date format dt/mnth/yr. dt shld store in 1 variable and month in another and yr in another variables.
Niek
October 30, 2012
:

Great code! How would i go about modifying this so that it splits a string with :, for example string "11:12" will be split into "11" and "12"?