gpt4 book ai didi

c - 从命令行输入解析字符串,移入数组

转载 作者:行者123 更新时间:2023-11-30 16:14:44 24 4
gpt4 key购买 nike

我正在尝试获取字符输入,使用非字母字符作为分隔符将它们分解为字符串,并将这些字符串移动到它们自己的数组中。我似乎无法获得该代码块的有效实现,这非常令人沮丧。如有任何帮助,我们将不胜感激。

char *ptr = strtok(arg1, " "); //pointer to the first token delimited by a space.
int i=0;
while (ptr != NULL) { //separate all the tokens and move each into the tokens array
new_num_tokens++;

if(new_num_tokens == num_tokens) { //need to allocate more memory
num_tokens += 2;
char *tmp = (char *)realloc(tokens, (num_tokens+1) * sizeof(char)); //num_tokens+1 for the null character
if(!tmp) {
printf("Could not reallocate memory");
return EXIT_FAILURE;
} else {
tokens = tmp;
}
}
strcpy(&tokens[i], ptr);

ptr = strtok(NULL, " ");
i+=sizeof(char);
}

未显示的是迭代整个输入并将所有非字母字符替换为空格的代码。我将 token 数量增加 2,以模拟将数组增加 2。

最佳答案

我通过将 char *tokens 数组转换为双指针 char **tokens 解决了这个问题,如下所述:

    char **tokens = malloc(sizeof(char *) * 2);
char *p = arg1;
for(; *p; p++) {
if (!isalpha(*p)) *p = ' '; //replace every nonalpha character with a space so we can use space
//as a delimiter in strtok()
}

char *ptr = strtok(arg1, " "); //pointer to the first token delimited by a space.
int i=0;
while (ptr != NULL) { //separate all the tokens and move each into the tokens array
new_num_tokens++;

if(new_num_tokens == num_tokens) { //need to allocate more memory
num_tokens += 2;
char **tmp = realloc(tokens, (num_tokens+1) * sizeof(char *)); //num_tokens+1 for the null character
if(!tmp) {
printf("Could not reallocate memory");
return EXIT_FAILURE;
} else {
tokens = tmp;
}
}
tokens[i] = ptr;

ptr = strtok(NULL, " ");
i++;
}

关于c - 从命令行输入解析字符串,移入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57445386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com