Skip to content

Instantly share code, notes, and snippets.

@EmilHernvall
Created May 3, 2011 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmilHernvall/953772 to your computer and use it in GitHub Desktop.
Save EmilHernvall/953772 to your computer and use it in GitHub Desktop.
A somewhat misguided c-implementation of the common split()-function present in most languages
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int explode(char*** ret, char* instr, char* delim)
{
char* str = strdup(instr);
char** arr = (char**)malloc(sizeof(char*) * (strlen(instr)+1));
int count = 0;
char* result = NULL;
result = strtok(str, delim);
while (result != NULL) {
arr[count] = strdup(result);
count++;
result = strtok(NULL, delim);
}
arr = (char**)realloc(arr, sizeof(char*) * (count+1));
*ret = arr;
free(str);
return count;
}
int main(void)
{
char* teststr = ":aderyn privmsg #c0la :hej på er allihop";
char** outbuf;
int n = explode(&outbuf, teststr, " ");
int i;
for (i = 0; i < n; i++) {
printf("%s\n", outbuf[i]);
free(outbuf[i]);
}
free(outbuf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment