Be wary of strtok()
; it is not re-entrant. Amongst other things, it means that if you need to call it in one function, and then call another function, and if that other function also uses strtok()
, your first function is messed up. It also writes NUL ('\0'
) bytes over the separators, so it modifies the input string as it goes. If you are looking for more than one terminator character, you can't tell which one was found. Further, if you write a library function for others to use, yet your function uses strtok()
, you must document the fact so that callers of your function are not bemused by the failures of their own code that uses strtok()
after calling your function. In other words, it is poisonous; if your function calls strtok()
, it makes your function unreusable, in general; similarly, your code that uses strtok()
cannot call other people's functions that also use it.
If you still like the idea of the functionality - some people do (but I almost invariably avoid it) - then look for strtok_r()
on your system. It is re-entrant; it takes an extra parameter which means that other functions can use strtok_r()
(or strtok()
) without affecting your function.
There are a variety of alternatives that might be appropriate. The obvious ones to consider are strchr()
, strrchr()
, strpbrk()
, strspn()
, strcspn()
: none of these modify the strings they analyze. All are part of Standard C (as is strtok()
), so they are essentially available everywhere. Looking for the material before a single character suggests that you should use strchr()
.