C将Char数组拆分为数组数组

时间:2017-03-30 17:06:12

标签: c arrays pointers char

我如何转换

char* string = "test test test test";

进入

char* array = ["test","test","test","test"];

如果数组的长度未知?

Ty人

1 个答案:

答案 0 :(得分:1)

如果允许修改内存,则可以执行此操作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *get_next_start(char *str, char delim, int terminate) {
    char *p;
    p = strchr(str, delim);
    if (p != NULL) {
        if (terminate) {
            /* only nul-terminate the string on the second pass */
            *p = '\0';
        }
        p += 1;
    }
    return p;
}

int main(void) {
    char string[] = "test test test test";
    char **string_list;
    char *p;
    size_t i;

    /* count the elements... */
    i = 0;
    for (p = string; p != NULL; p = get_next_start(p, ' ', 0)) {
        i += 1;
    }
    printf("items: %zd\n", i);

    /* get some memory for the table */
    string_list = malloc(sizeof(string_list) * (i + 1));

    /* populate the table */
    i = 0;
    for (p = string; p != NULL; p = get_next_start(p, ' ', 1)) {
        string_list[i] = p; /* store the next item... */
        i += 1;
    }
    string_list[i] = NULL; /* terminate the list with NULL */

    /* print the table */
    for (i = 0; string_list[i] != NULL; i++) {
        printf("%3zd: [%s]\n", i, string_list[i]);
    }

    /* free the memory */
    free(string_list);

    return 0;
}

请注意string ...

的声明
  • char string[] = "test test test test"将数据放在堆栈上
  • char *string = "test test test test"将数据放入只读内存

如果您不允许修改内存并希望单次传递,则可以使用strndup()复制字符串,使用realloc()分配和调整表格大小。

相关问题