[英]Splitting a user-entered String into separate tokens by white space in C
[英]Splitting a string by space in C
我正在使用C并通过套接字我将收到一个带有一个空格的消息,我需要将字符串拆分为空格中的部分。 我该怎么做呢?
strtok_r是你的朋友。
不要使用plain strtok()
,因为它不是线程安全的。
即使在线程安全的平台上(因为状态保存在线程局部存储中),仍然存在使用内部状态意味着无法同时解析多个字符串中的令牌的问题。
例如,如果您编写一个使用strtok()
来分隔字符串A的函数,则无法在使用strtok()
拆分字符串B的第二个函数的循环内调用您的函数。
如果你拥有字符串缓冲区,并且知道修改是安全的,你可以像人们建议的那样使用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'.
}
根据上下文,这可能更快和/或更容易理解。
这通常使用strtok ()库调用来完成。 但是,请注意,此函数将修改输入字符串(它会在找到所选分隔符的位置插入'\\ 0'NUL字符) - 因此,如果需要,您可能需要在字符串的副本上调用strtok()以后访问整个事情。
编辑:正如另一张海报所提到的,“plain”strtok()不是线程安全的,所以strtok_r()是更安全的函数。 我不确定strtok_r()是否存在同样修改输入缓冲区的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.