C:从分隔的源字符串创建字符串数组 [英] C: creating array of strings from delimited source string
问题描述
在 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 处理过的字符串 char *myarray[]
的 malloc 处理过的数组,这样:
The source string will always have only a single space as the delimiter. And I would like a malloc'ed array of malloc'ed strings char *myarray[]
such that:
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:从分隔的源字符串创建字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!