如何转换
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/