我是C初学者,请不要攻击我。 所以,我有这个函数来获取“ip/mask”类型字符串的掩码:
char *getmask(char n[]) {
char x[255] = { 0 };
strcpy(x, n);
char *mask;
mask = strtok(x, "/");
mask = strtok(NULL, "/");
return mask;
}
问题是我需要对一个字符串中的多个“ip/mask”执行此操作。所以当我这样做时:
net = strtok(x4, " ");
net = strtok(NULL, " ");
while (net != NULL) {
net = strtok(NULL, " ");
strcpy(masca, "\n");
strcpy(masca, getmask(net));
//some other code
}
问题是 strtok()
发生故障,因为我首先调用它,但随后在 getmask(net)
中再次调用它。
有办法绕过它吗?如果没有,我还能如何分割字符串?
最佳答案
使用strtok_r()。它与 strtok 的行为相同,但允许您“同时”处理多个字符串。
char *strtok_r(char *str, const char *delim, char **saveptr);
The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.
On the first call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored. In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.
Different strings may be parsed concurrently using sequences of calls to strtok_r() that specify different saveptr arguments.
来源:Linux man strtok_r
关于c - 如何在没有 strtok 的情况下分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40335514/