在C中按空格拆分字符串

The*_*i.9 7 c string

我正在使用C并通过套接字我将收到一个带有一个空格的消息,我需要将字符串拆分为空格中的部分.我该怎么做呢?

Rod*_*ddy 14

strtok_r是你的朋友.

不要使用plain strtok(),因为它不是线程安全的.

即使在线程安全的平台上(因为状态保存在线程局部存储中),仍然存在使用内部状态意味着无法同时解析多个字符串中的令牌的问题.

例如,如果您编写一个strtok()用于分隔字符串A的函数,则无法在strtok()用于拆分字符串B 的第二个函数的循环内调用您的函数.


unw*_*ind 5

如果您拥有字符串缓冲区,并且知道可以安全地修改,您可以strtok_r()按照人们的建议使用.或者你可以自己做,像这样:

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'.
}
Run Code Online (Sandbox Code Playgroud)

根据上下文,这可能更快和/或更容易理解.