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*.

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

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟