Skip to content

Instantly share code, notes, and snippets.

@carun
Created November 20, 2012 12:20
Show Gist options
  • Save carun/4117614 to your computer and use it in GitHub Desktop.
Save carun/4117614 to your computer and use it in GitHub Desktop.
Explode in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **explode(char *string, char separator, int *arraySize)
{
int start = 0, i, k = 0, count = 2;
char **strarr;
for (i = 0; string[i] != '\0'; i++){
/* Number of elements in the array */
if (string[i] == separator){
count++;
}
}
arraySize[0] = count-1;
/* count is at least 2 to make room for the entire string
* and the ending NULL */
strarr = calloc(count, sizeof(char*));
i = 0;
while (*string != '\0') {
if (*string == separator) {
strarr[i] = calloc(k - start + 2,sizeof(char));
strncpy(strarr[i], string - k + start, k - start);
strarr[i][k - start + 1] = '\0'; /* ensure null termination */
start = k;
start++;
i++;
}
string++;
k++;
}
/* copy the last part of the string after the last separator */
strarr[i] = calloc(k - start + 1,sizeof(char));
strncpy(strarr[i], string - k + start, k - start);
strarr[++i] = NULL;
return strarr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment