Need help in strtok function
#include<stdio.h>
#include<string.h>
int main()
{
char string[100], *ptr = NULL;
memset(string, 0, 100);
strcpy(string, "abc#efg#xyz");
ptr = strtok(string, "#");
fprintf(stderr, "ptr = [%s]\n", ptr);
ptr = strtok(NULL, "#");
fprintf(stderr, "ptr = [%s]\n", ptr);
ptr = strtok(NULL, "#");
fprintf(stderr, "ptr = [%s]\n", ptr);
return 0;
}
The output is
ptr = [abc]
ptr = [efg]
ptr = [xyz]
This is fine, but when if the first token is null then the first call to strtok returns the second token. My understanding is that it will return a null in the first call as the token is not present.
#include<stdio.h>
#include<string.h>
int main()
{
char string[100], *ptr = NULL;
memset(string, 0, 100);
strcpy(string, "#efg#xyz");
ptr = strtok(string, "#");
fprintf(stderr, "ptr = [%s]\n", ptr);
ptr = strtok(NULL, "#");
fprintf(stderr, "ptr = [%s]\n", ptr);
ptr = strtok(NULL, "#");
fprintf(stderr, "ptr = [%s]\n", ptr);
return 0;
}***
The output is
ptr = [efg]
ptr = [xyz]
ptr = [(null)]
strtok()
source code – Bradberry