add: split
This commit is contained in:
parent
949cbd7355
commit
c14b4fcdd8
54
src/str/split.c
Normal file
54
src/str/split.c
Normal file
@ -0,0 +1,54 @@
|
||||
#include "str.h"
|
||||
|
||||
static void free_tab(char **tab)
|
||||
{
|
||||
for (size_t i = 0; tab[i] != NULL; i++)
|
||||
free(tab);
|
||||
free(tab);
|
||||
}
|
||||
|
||||
static ssize_t fill_tab(const char *str, const char *delimiter, char **tab)
|
||||
{
|
||||
size_t len = 0;
|
||||
size_t delimiter_len = strlen(delimiter);
|
||||
const char* tmp = str;
|
||||
const char* next;
|
||||
|
||||
while (tmp != NULL)
|
||||
{
|
||||
while (strcmp(tmp, delimiter) == 0)
|
||||
tmp += delimiter_len;
|
||||
next = strstr(tmp, delimiter);
|
||||
if (tab != NULL)
|
||||
{
|
||||
if (next == NULL)
|
||||
tab[len] = strndup(tmp, strlen(tmp));
|
||||
else
|
||||
tab[len] = strndup(tmp, next - tmp);
|
||||
if (tab[len] == NULL)
|
||||
{
|
||||
free_tab(tab);
|
||||
return (-1);
|
||||
}
|
||||
}
|
||||
len++;
|
||||
tmp = next;
|
||||
}
|
||||
if (tab != NULL)
|
||||
tab[len] = NULL;
|
||||
return (len);
|
||||
}
|
||||
|
||||
char **split(const char *str, const char *delimiter)
|
||||
{
|
||||
ssize_t len;
|
||||
char **tab;
|
||||
|
||||
len = fill_tab(str, delimiter, NULL);
|
||||
tab = malloc((len + 1) * sizeof(char *));
|
||||
if (tab == NULL)
|
||||
return (NULL);
|
||||
if (fill_tab(str, delimiter, tab) == -1)
|
||||
return (NULL);
|
||||
return (tab);
|
||||
}
|
6
src/str/str.h
Normal file
6
src/str/str.h
Normal file
@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
char **split(const char *str, const char *delimiter);
|
Loading…
Reference in New Issue
Block a user