Saturday, August 22, 2009

A simple example of strtok

Tokenizing a string is always a cumbersome process and most of times results in a buggy code.
Here by presents a very simple example of strtok,


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

int main() {

char *token;
char *lasts;
char buf[50] ;

strcpy(buf,"3/4/5/**6*7");
printf("\ntokenizing %s with strtok_r():\n", buf);

if ((token = strtok_r(buf, "*/", &lasts)) != NULL) {

printf("token = %s\n", token);
while ((token = strtok_r(NULL, "*/", &lasts)) != NULL) {
printf("token = %s\n", token);

}
}
}

Output:

tokenizing 3/4/5/**6*7 with strtok_r()

token = 3

token = 4


token = 5


token = 6


token = 7

The
strtok() function uses a static buffer while parsing, so it's not thread safe. Use strtok_r() if this matters to you.

No comments:

Post a Comment