strtok 无法标记化?
在下面,我尝试使用 strok
拆分字符串而不创建副本
#include <string.h>
void func(char *c)
{
char *pch = strtok (c,"#");
while (pch != NULL)
{
pch = strtok (NULL, "#");
}
}
int main()
{
char c[] = "a#a\nb#b\n";
char *pch = strtok (c,"\n");
while (pch != NULL)
{
char *p = new char[strlen(pch)+1];
strcpy(p, pch);
func(p); //copy of pch
pch = strtok (NULL, "\n"); //fails to get pointer to 'b#b'
}
}
In the following, I'm trying to split string without creating copies using strok
#include <string.h>
void func(char *c)
{
char *pch = strtok (c,"#");
while (pch != NULL)
{
pch = strtok (NULL, "#");
}
}
int main()
{
char c[] = "a#a\nb#b\n";
char *pch = strtok (c,"\n");
while (pch != NULL)
{
char *p = new char[strlen(pch)+1];
strcpy(p, pch);
func(p); //copy of pch
pch = strtok (NULL, "\n"); //fails to get pointer to 'b#b'
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯...
strtok()
可以将标记化字符串存储在静态缓冲区中。因此,当在func()
中调用第二个strtok()
时,第一个操作的结果(在main()
中)似乎丢失。看一下strtok_r()
。Uhm...
strtok()
may store the tokenized string in a static buffer. Hence, when secondstrtok()
is called in thefunc()
, the results of the first operation (in themain()
) seem to be lost. Take a look atstrtok_r()
.strtok 使用静态变量,因此它不能重入并且永远不是线程安全的。
strtok_r 不是 C89/C99,仅限 POSIX。
strtok use static variables, therefore it cannot work reentrant and is never threadsafe.
strtok_r is not C89/C99 only POSIX.