问题描述
这将是一个分隔的字符串转换为字符串在C(不是C ++)阵列的有效途径?例如,我可能有:
What would be an efficient way of converting a delimited string into an array of strings in C (not C++)? For example, I might have:
char *input = "valgrind --leak-check=yes --track-origins=yes ./a.out"
源字符串永远只有一个空格作为分隔符。我想malloc分配的字符串数组malloc分配的char * myArray的[]
这样:
myarray[0]=="valgrind"
myarray[1]=="--leak-check=yes"
...
修改我要假设有在 inputString
,所以我不能只是将其限制在10令牌任意数量或一些东西。
Edit I have to assume that there are an arbitrary number of tokens in the inputString
so I can't just limit it to 10 or something.
我已经尝试与 strtok的
凌乱的解决方案,并链表我已经实现,但抱怨Valgrind的这么多,我就放弃了。
I've attempted a messy solution with strtok
and a linked list I've implemented, but valgrind complained so much that I gave up.
(如果你想知道,这是一个基本的Unix shell我试着写。)
(If you're wondering, this is for a basic Unix shell I'm trying to write.)
推荐答案
什么是关于这样的:
char* string = "valgrind --leak-check=yes --track-origins=yes ./a.out";
char** args = (char**)malloc(MAX_ARGS*sizeof(char*));
memset(args, 0, sizeof(char*)*MAX_ARGS);
char* curToken = strtok(string, " \t");
for (int i = 0; curToken != NULL; ++i)
{
args[i] = strdup(curToken);
curToken = strtok(NULL, " \t");
}
这篇关于C:从分隔源字符串创建字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!