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

标签 c arrays pointers char

如何转换

char* string = "test test test test";

进入

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

如果数组的长度未知?

你们这些人

最佳答案

如果您被允许修改内存,那么您可以执行以下操作:

#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()分配表并调整其大小。

关于C 将 Char 数组拆分为数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124179/

相关文章:

c - Microchip PIC led flash OR 操作罕见行为

javascript - 有没有一种优雅的方法可以将变量名中的单个单词提取到数组中?

PHP AJAX 排序数组无需重新加载页面

使用 realloc 将 CSV 文件保存在数组中

c - 为什么 C 语言中可以给指针变量赋值?

c++ - 将图像从 C++ 传递给 Haskell 并取回一个字符串

python - 实现 AirDrop 协议(protocol)

时序测量的困惑

c - 找到平均值的更好算法

php - 遍历索引数组