c - 如何在没有 strtok 的情况下分割字符串?

标签 c string strtok c-strings

我是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/

相关文章:

c - 优雅地加密/解密脚本的建议?[现在在 Sourceforge 上]

c - 格雷码递增函数

c - 结构作为函数的返回类型

c++ 在比较字符串时忽略前面的空格,例如 : "str1"compare. ("str2") = TRUE

string - 用于在句点之间获取字符串中特定值的公式

c - 我如何获得C中由分隔符分隔的标记的位置

c - 如何使用 clock_gettime

java - 在字符串正则表达式 C/W 中查找重复的单词

c - strtok() 作为 printf() 中的参数反向打印值

c - Strtok 问题 C(EOF 字符?)