Skip to content

Instantly share code, notes, and snippets.

@nbulischeck
Created February 26, 2018 03:52
Show Gist options
  • Save nbulischeck/99bf0591662fc6ee73df165343627f47 to your computer and use it in GitHub Desktop.
Save nbulischeck/99bf0591662fc6ee73df165343627f47 to your computer and use it in GitHub Desktop.
Frustrated with strtok? Partition parses strings based on strings instead of characters and doesn't fudge the target string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct view { const char *s; size_t len; };
size_t partition(struct view *result, size_t n,
const char *str, const char *delim){
char *startp = (char *)str, *endp;
size_t l = strlen(delim), i = 0;
while ((endp = strstr(startp, delim)) && (i < n)){
size_t diff = endp - startp;
if (diff){
(result+i)->s = startp;
(result+i++)->len = diff;
}
startp = endp + l;
}
if ((*startp) && (i < n)){
(result+i)->s = startp;
(result+i++)->len = strlen(startp);
}
return (i > n) ? n : i;
}
char **instantiate(struct view *result, size_t size){
int i;
char **strings = malloc((size+1) * sizeof(char *));
for (i = 0; i < size; i++){
strings[i] = malloc(((result+i)->len+1) * sizeof(char));
strncpy(strings[i], (result+i)->s, (result+i)->len);
strings[i][(result+i)->len] = '\0';
}
strings[size] = NULL;
return strings;
}
void destroy(char **args){
int i = 0;
while (args[i]){
free(args[i++]);
} free(args);
}
int main(){
int i = 0;
size_t n = 1024, ret = 0;
char **strings;
struct view *result = malloc(n * sizeof(struct view));
ret = partition(result, n, "foobarfoobarfoobarfoobar", "foo");
strings = instantiate(result, ret);
for (i = 0; i < ret; i++){
printf("%s\n", strings[i]);
}
destroy(strings);
free(result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment