Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string by space in C

Tags:

c

string

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?

like image 644
The.Anti.9 Avatar asked Nov 27 '08 09:11

The.Anti.9


2 Answers

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.

like image 90
Roddy Avatar answered Oct 25 '22 04:10

Roddy


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.

like image 23
unwind Avatar answered Oct 25 '22 03:10

unwind