Created
July 13, 2011 20:21
-
-
Save FurryHead/1081231 to your computer and use it in GitHub Desktop.
C split/join functions, using strtok_r -- Source
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include "string_sj.h" | |
int str_split(const char* src, const char* delims, char*** dest) { | |
char *s = strdup(src); | |
char *c, *saveptr, *tmp; | |
void *_tmp; | |
int num_tokens = 0, num_size = 10; | |
c = strtok_r(s, delims, &saveptr); | |
if (c == NULL) | |
return 0; | |
*dest = malloc(num_size * sizeof(char*)); | |
if (*dest == NULL) | |
return -1; | |
tmp = strdup(c); | |
if (tmp == NULL) { | |
free(*dest); | |
free(s); | |
*dest = NULL; | |
return -1; | |
} | |
(*dest)[num_tokens] = tmp; | |
num_tokens++; | |
while ((c = strtok_r(NULL, delims, &saveptr)) != NULL) { | |
if (num_tokens == num_size) { | |
num_size += 10; | |
_tmp = realloc(*dest, num_size*sizeof(char*)); | |
if (!_tmp) { | |
fprintf(stderr, "ERROR: split() cannot realloc() memory needed."); | |
return -1; | |
} | |
*dest = (char**)_tmp; | |
} | |
tmp = strdup(c); | |
if (tmp == NULL) { | |
free(*dest); | |
free(s); | |
*dest = NULL; | |
return -1; | |
} | |
(*dest)[num_tokens] = tmp; | |
num_tokens++; | |
} | |
return num_tokens; | |
} | |
char *str_join(char** items, int start, int end, const char* delim) { | |
int i; | |
char *tmp = NULL; | |
int dlen = strlen(delim); | |
int total_size = 0; | |
if ((end - start) < 1 || start >= end) { | |
return strdup(""); | |
} else if ((end - start) == 1) { | |
return strdup(items[start]); | |
} | |
total_size += strlen(items[start]); | |
for (i = start+1; i < end; i++) { | |
total_size += dlen; | |
total_size += strlen(items[i]); | |
} | |
tmp = (char*)malloc(total_size * sizeof(char)); | |
if (tmp == NULL) | |
return NULL; | |
strcat(tmp, items[start]); | |
for (i = start+1; i < end; i++) { | |
strcat(tmp, delim); | |
strcat(tmp, items[i]); | |
} | |
return tmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment