doudie2693 2014-01-25 13:08
浏览 37
已采纳

C替代PHP爆炸功能

So, i'm looking for a C function that does the equivalent to PHP's explode function. For those who are not familiar: Explode grabs a string and parses each entry separated by the given char/escape sequence. the best part about this function is its return value, which is an already forged array with all the entries. problem is, this doesn't seem to exist in C. the closest function available is strchr but it returns only a pointer to the first ocurrence of the split.

edit: here's the function, although it has a different behaviour (like the return value differs) it's what i want.

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;
}

it's possible to call it this way:

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

1条回答 默认 最新

  • dongmi1221 2014-01-25 13:15
    关注

    Use strtok(). From the man page for it:

    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.

    In other words, loop through your string and keep calling strtok() until it returns NULL in order to get all the words (that would be split on the delimiters specified to the first call of strtok()) returned as char*.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算