C: creating array of strings from delimited source string

前端 未结 5 1550
野的像风
野的像风 2020-12-10 07:52

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         


        
5条回答
  •  醉话见心
    2020-12-10 08:45

    if you have all of the input in input to begin with then you can never have more tokens than strlen(input). If you don't allow "" as a token, then you can never have more than strlen(input)/2 tokens. So unless input is huge you can safely write.

    char ** myarray = malloc( (strlen(input)/2) * sizeof(char*) );
    
    int NumActualTokens = 0;
    while (char * pToken = get_token_copy(input))
    { 
       myarray[++NumActualTokens] = pToken;
       input = skip_token(input);
    }
    
    char ** myarray = (char**) realloc(myarray, NumActualTokens * sizeof(char*));
    

    As a further optimization, you can keep input around and just replace spaces with \0 and put pointers into the input buffer into myarray[]. No need for a separate malloc for each token unless for some reason you need to free them individually.

提交回复
热议问题