gpt4 book ai didi

C 将字符串拆分为单个单词并将单个单词保存在数组中

转载 作者:行者123 更新时间:2023-11-30 17:05:42 26 4
gpt4 key购买 nike

假设用户输入“程序一二三”。我将其保存在 userTyped 数组中并将其传递给 parse() 函数。我需要 parse() 函数来实现

userargv[0]是程序

userargv[1] 是一个

userargv[2] 是二

等等

我可以看出它一定是涉及指针的东西,但我无法弄清楚。代码如下:

int main(int argc, char **argv)
{
char userTyped[1000];

char* userargv[100];//this is where i need the parse() function to store the arguments to pass to execv

printf("typesomething>");

fgets(userTyped, 1000, stdin);

parse(userTyped, &userargv);

return 0;
}



int parse(char* userTyped, char* userargv){

const char whitespace[2] = " "; //the deliminator
char *strings;

strings = strtok(userTyped, whitespace);

while( strings != NULL )
{
strings = strtok(NULL, whitespace);

}
//THIS ALL WORKS, BUT I NEED TO DO SOMETHING LIKE userargv[i] = strings;
//OR *userargv[i] = &strings;
//OR SOMETHING LIKE THAT.

return 0;
}

最佳答案

您必须分配一个字符串数组(char**),并分配它的每个元素,然后将所有找到的字符串复制回其中;

// nb: the function prototype has been slightly modified 
char** parse(char* userTyped, int *nargs){

const char whitespace[2] = " "; //the deliminator
char *strings;
char **arr;
int n = 0; // initially no element allocated

strings = strtok(userTyped, whitespace);

while( strings != NULL )
{
if( n ){ // if there are already allocated elements?
arr = realloc( arr, ( n + 1 ) * sizeof( char** ) );
}else{
arr = malloc( ( n + 1 ) * sizeof( char* ) );
}

if( !arr ){
perror( "parse" );
exit( -1 );
}

// duplicate strings
arr[ n ] = malloc( strlen( strings )+1 );

if( !arr[ n ] ){
perror( "parse" );
exit( -2 );
}
strcpy(arr[ n ] , strings); // make a copy of the string

n++;

strings = strtok(NULL, whitespace);

}


// call freeStrArr when done with arr;
//
*nargs = n; // save array size;
return arr; // return string array
}

// this how to free the returned array;
void freeStrArr(char ** strarr,int n){
while( n ){
n--;
free( strarr[ n ] );
}
free( strarr);
}

关于C 将字符串拆分为单个单词并将单个单词保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35142683/

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