gpt4 book ai didi

php - PHP explode 函数的 C 替代方案

转载 作者:行者123 更新时间:2023-11-30 15:39:42 26 4
gpt4 key购买 nike

所以,我正在寻找一个 C 函数,它的作用相当于 PHP 的 explode 函数。对于那些不熟悉的人:Explode 获取一个字符串并解析由给定的字符/转义序列分隔的每个条目。这个函数最好的部分是它的返回值,它是一个已经伪造的包含所有条目的数组。问题是,这在 C 中似乎不存在。最接近的可用函数是 strchr,但它仅返回指向第一次出现拆分的指针。

编辑:这是函数,尽管它有不同的行为(例如返回值不同),但这就是我想要的。

int explode(char* str, char* delim, char ***r) {
char **res = (char**) malloc(sizeof(char*) * strlen(str));
char *p;
int i = 0;
while (p = strtok(str, delim)) {
res[i] = malloc(strlen(p) + 1);
strcpy(res[i], p);
++i;
str = NULL;
}
res = realloc(res, sizeof(char*) * i);
*r = res;
return i;
}

可以这样调用它:

char str[] = "test1|test2|test3";
char** res;
int count = explode(str, "|", &res);
int i;
for (i = 0; i < count; ++i) {
printf("%s\n", res[i]);
free(res[i]);
}
free(res);

最佳答案

使用strtok()。从它的手册页:

The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.

换句话说,循环遍历字符串并继续调用 strtok() 直到返回 NULL 以获得所有单词(将在分隔符上分割)指定为第一次调用 strtok()),返回为 char*

关于php - PHP explode 函数的 C 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21350952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com