You probably don't want strtok
to begin with, as it leaves you no way of figuring what character was eliminated (except if you have a spare copy of the string).
strtok
is not a straightforward API and is easy to misunderstand.
Quoting the manpage:
The strtok() and strtok_r() functions return a pointer to the beginning of
each subsequent token in the string, after replacing the token itself with
a NUL character. When no more tokens remain, a null pointer is returned.
Your problem probably means you've fallen to the obscurity of the algorithm. Suppose this string:
char* value = "foo < bar & baz > frob";
The first time you call strtok
:
char* ptr = strtok(value, "<>&");
strtok
will return you the value
pointer, except that it will have modified the string to this:
"foo \0 bar & baz > frob"
As you may notice, it changed the <
to a NUL
. Now, however, if you use value
, you'll get "foo "
since there's a NUL
in the middle of the way.
Subsequent calls to strtok
with NULL
will proceed through the string, until you've reached the end of the string, at which point you'll get NULL
.
char* str = "foo < bar & frob > nicate";
printf("%s\n", strtok(str, "<>&")); // prints "foo "
printf("%s\n", strtok(NULL, "<>&")); // prints " bar "
printf("%s\n", strtok(NULL, "<>&")); // prints " frob "
printf("%s\n", strtok(NULL, "<>&")); // prints " nicate"
assert(strtok(NULL, "<>&") == NULL); // should be true
It would be fairly straightforward to write a function that replaces the contents without strtok
, either dealing with the hard work yourself, or getting help from strpbrk
and strcat
.