I'm working with C and through a socket I will be receiving a message with one space in it, I need to split the string into parts at the space. How would I go about doing this?
strtok_r is your friend.
Don't use plain strtok()
, as it's NOT thread-safe.
Even on platforms where it is thread-safe (because the state is held in Thread-Local Storage), there is still the problem that the use of internal state means you cannot parse tokens from several strings simultaneously.
for example, if you write a function which uses strtok()
to separate string A, your function cannot be called within the loop of a second function which is using strtok()
to split string B.
If you own the string buffer, and know that it is safe to modify, you can use strtok_r()
as people have suggested. Or you could do it yourself, like this:
char buffer[2048];
char *sp;
/* read packet into buffer here, omitted */
/* now find that space. */
sp = strchr(buffer, ' ');
if(sp != NULL)
{
/* 0-terminate the first part, by replacing the space with a '\0'. */
*sp++ = '\0';
/* at this point we have the first part in 'buffer', the second at 'sp'.
}
This might be faster and/or easier to understand, depending on context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With