Let's say I'm using strtok()
like this..
char *token = strtok(input, ";-/");
Is there a way to figure out which token actually gets used? For instance, if the inputs was something like:
Hello there; How are you? / I'm good - End
Can I figure out which delimiter was used for each token? I need to be able to output a specific message, depending on the delimiter that followed the token.
Important:
strtok
is not re-entrant, you should usestrtok_r
instead of it.You can do it by saving a copy of the original string, and looking into offsets of the current token into that copy:
This prints
Demo #1
EDIT: Handling multiple delimiters
If you need to handle multiple delimiters, determining the length of the current sequence of delimiters becomes slightly harder: now you need to find the next token before deciding how long is the sequence of delimiters. The math is not complicated, as long as you remember that
NULL
requires special treatment:Demo #2
You can't.
strtok
overwrites the next separator character with a nul character (in order to terminate the token that it's returning this time), and it doesn't store the previous value that it overwrites. The first time you callstrtok
on your example string, the;
is gone forever.You could do something if you keep an unmodified copy of the string you're modifying with
strtok
- given the index of the nul terminator for your current token (relative to the start of the string), you can look at the same index in the copy and see what was there.That might be worse than just writing your own code to separate the string, of course. You can use
strpbrk
orstrcspn
, if you can live with the resulting token not being nul-terminated for you.But with a little pointer arithmetic you can do something like: