Splitting a string at a delimiter and storing subs

2019-09-20 08:53发布

I want to write a function that splits a string given by the user on the command-line by the first occurrence of a comma and put in an array.

This is what I've tried doing:

char**split_comma(const str *s) {
    char *s_copy = s;

    char *comma = strchr(s_copy, ",");

    char **array[2];
    *(array[0]) = strtok(s_copy, comma);
    *(array[1]) = strtok(NULL,comma);
return array;
}

This is the main function:

int main(int argc, char **argv) {
   char **r = split_comma(argv[1]);
   printf("substring 1: %s, substring 2: %s\n", r[0],r[1]);
   return 0;
}

Can someone please give me some insight as to why this doesn't work?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-20 09:26

This is working.

char **split_on_comma(const char *s) {
    char ** result;
    result = malloc(sizeof(char*)*2);
    result[0] = malloc(sizeof(char) *200);
    result[1] = malloc(sizeof(char) *200);
    char *position;
    position = strchr(s, ',');
    strcpy(result[1], position +1);
    strncpy(result[0], s, position -s);
    return result;
}
查看更多
我只想做你的唯一
3楼-- · 2019-09-20 09:29

You need to allocate enough space for the 2 destination char buffers first and second.

Here's a simple solution where we first duplicate the input string s, then find the comma and replace it with a string terminator character (0). The first string then is at the beginning of s , and the second string is after the 0:

/* Caller must call free() on first */
void split_comma( char* s, char** first, char** second )
{
    char* comma;
    if(!s||!first||!second) return ;
    *first = strdup(s) ;
    comma=strchr(*first,',') ;
    if(comma) {
        *comma = 0 ;
        *second = comma + 1 ;
    } else *second = 0 ;
}
查看更多
登录 后发表回答