Split string with delimiters in C

2018-12-31 02:17发布

How do I write a function to split and return an array for a string with delimiters in the C programming language?

char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
str_split(str,',');

标签: c string split
25条回答
梦该遗忘
2楼-- · 2018-12-31 03:09

Yet another answer (this was moved here from here):

Try to use the strtok function:

see details on this topic here or here

The issue here is that you have to process the words immediately. If you want to store it in an array you have to allocate the correct size for it witch is unknown.

So for example:

char **Split(char *in_text, char *in_sep)
{
    char **ret = NULL;
    int count = 0;
    char *tmp = strdup(in_text);
    char *pos = tmp;

    // This is the pass ONE: we count 
    while ((pos = strtok(pos, in_sep)) != NULL)
    {
        count++;
        pos = NULL;
    }

    // NOTE: the function strtok changes the content of the string! So we free and duplicate it again! 
    free(tmp);
    pos = tmp = strdup(in_text);

    // We create a NULL terminated array hence the +1
    ret = calloc(count+1, sizeof(char*));
    // TODO: You have to test the `ret` for NULL here

    // This is the pass TWO: we store
    count = 0;
    while ((pos = strtok(pos, in_sep)) != NULL)
    {
        ret[count] = strdup(pos);
        count++;
        pos = NULL;
    }
    free(tmp);

    return count;
}

// Use this to free
void Free_Array(char** in_array)
{
    char *pos = in_array;

    while (pos[0] != NULL)
    {
        free(pos[0]);
        pos++;

    }

    free(in_array);

}

Note: We use the same loop and function to calculate the counts (pass one) and for making the copies (pass two), in order to avoid allocation problems.

Note 2: You may use some other implementation of the strtok the reasons mention in separate posts.

You can use this like:

int main(void)
{
  char **array = Split("Hello World!", " ");
  // Now you have the array
  // ...

  // Then free the memory
  Free_Array(array);
  array = NULL;
  return 0;
}

(I did not test it, so please let me know if it does not work!)

查看更多
登录 后发表回答