Hoppa till huvudinnehållet
Institutionen för informationsteknologi

A simple explode() function in C

Note: Everything on this page is presented as is. The code is public domain, university copyright rules do not apply.

Most languages that handle string objects have an explode() function, i.e. a function that converts a delimited string into a string array. C doesn't have one, and scouring the internet I have failed to find one readily available. So here is one.

It's fairly simple stuff, but the function contains some pointer arithmetic, which some may find awkward to use. Therefore I'm leaving the function here:

#include <stdlib.h>
#include <string.h>

int explode(char ***arr_ptr, char *str, char delimiter)
{
  char *src = str, *end, *dst;
  char **arr;
  int size = 1, i;

  // Find number of strings
  while ((end = strchr(src, delimiter)) != NULL)
    {
      ++size;
      src = end + 1;
    }

  arr = malloc(size * sizeof(char *) + (strlen(str) + 1) * sizeof(char));

  src = str;
  dst = (char *) arr + size * sizeof(char *);
  for (i = 0; i < size; ++i)
    {
      if ((end = strchr(src, delimiter)) == NULL)
        end = src + strlen(src);
      arr[i] = dst;
      strncpy(dst, src, end - src);
      dst[end - src] = '\0';
      dst += end - src + 1;
      src = end + 1;
    }
  *arr_ptr = arr;

  return size;
}

Example

char **arr, *str = "sen massa  strings";
int size, i;

size = explode(&arr, str, ' ');

for (i = 0; i < size; ++i)
  printf("\"%s\"\n", arr[i]);
printf("\n");

free(arr);

size = explode(&arr, str, 's');

for (i = 0; i < size; ++i)
  printf("\"%s\"\n", arr[i]);

free(arr);

This returns the output:

"sen"
"massa"
""
"strings"

""
"en ma"
""
"a "
"tring"
""

Uppdaterad  2011-04-27 13:11:43 av Lars Melander.