libcdsb/src/string/extra-split.c
2022-06-02 15:53:09 +03:00

90 lines
1.8 KiB
C

/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2022 Gregory Lirent */
#include "include.h"
arr_t string_split_cstring(const str_t* s, const char* a, size_t maxn) {
arr_t x = { .mem = 0, .size = 0, .type = VTYPE_STRING };
size_t n;
char* p;
char* e;
str_t* v;
if (is_null(s->buffer)) {
return x;
}
if (is_null(a) || !*a) {
v = x.mem = malloc(sizeof(str_t));
v->buffer = strdup(s->buffer);
return x;
}
n = strlen(a);
p = s->buffer;
e = p;
while (maxn-- && !is_null(p = strstr(p, a))) {
p += n;
v = x.mem = realloc(x.mem, ++x.size*sizeof(str_t));
v[x.size-1].buffer = strndup(e, p - e);
p += n;
e = p;
}
if (*e) {
n = strlen(e);
v = x.mem = realloc(x.mem, ++x.size*sizeof(str_t));
v[x.size-1].buffer = strndup(e, n);
}
return x;
}
arr_t string_split_char(const str_t* s, int ac, size_t maxn) {
arr_t x = { .mem = 0, .size = 0, .type = VTYPE_STRING };
char a[5] = { 0 };
size_t n;
char* p;
char* e;
str_t* v;
if (is_null(s->buffer)) {
return x;
}
if (is_null(p = tochar_unicode(a, ac)) || !(n = p - a)) {
v = x.mem = malloc(sizeof(str_t));
v->buffer = strdup(s->buffer);
return x;
}
p = s->buffer;
e = p;
while (maxn-- && !is_null(p = strstr(p, a))) {
p += n;
v = x.mem = realloc(x.mem, ++x.size*sizeof(str_t));
v[x.size-1].buffer = strndup(e, p - e);
p += n;
e = p;
}
if (*e) {
n = strlen(e);
v = x.mem = realloc(x.mem, ++x.size*sizeof(str_t));
v[x.size-1].buffer = strndup(e, n);
}
return x;
}