Created
September 11, 2023 00:00
-
-
Save kmbenjel/3ae9a8d188cc54ad9ddde6de3e71c7d1 to your computer and use it in GitHub Desktop.
This file contains 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
/* ************************************************************************** */ | |
/* */ | |
/* ::: :::::::: */ | |
/* ft_split.c :+: :+: :+: */ | |
/* +:+ +:+ +:+ */ | |
/* By: kbenjel <[email protected]> +#+ +:+ +#+ */ | |
/* +#+#+#+#+#+ +#+ */ | |
/* Created: 2023/09/07 02:58:22 by kbenjel #+# #+# */ | |
/* Updated: 2023/09/08 03:59:10 by kbenjel ### ########.fr */ | |
/* */ | |
/* ************************************************************************** */ | |
#include <stdlib.h> | |
char **free_previous(char **splits) | |
{ | |
int i; | |
i = -1; | |
while (splits[++i]) | |
free(splits[i]); | |
free(splits); | |
return (NULL); | |
} | |
int is_separator(char c, char *charset) | |
{ | |
int i; | |
i = 0; | |
if (!charset) | |
return (0); | |
while (charset[i]) | |
{ | |
if (charset[i] == c) | |
return (1); | |
i++; | |
} | |
return (0); | |
} | |
int substring_count(char *str, char *charset) | |
{ | |
int count; | |
int i; | |
count = 0; | |
i = -1; | |
if (!str || !charset) | |
return (0); | |
while (str[++i]) | |
{ | |
if (!is_separator(str[i], charset)) | |
{ | |
count++; | |
while (str[i] && !is_separator(str[i], charset)) | |
i++; | |
} | |
} | |
return (count); | |
} | |
char **fill_splits(char **splits, char *str, char *charset) | |
{ | |
int i[3]; | |
i[0] = -1; | |
i[1] = 0; | |
i[2] = 0; | |
while (str[++i[0]]) | |
{ | |
if (!is_separator(str[i[0]], charset)) | |
{ | |
i[2] = 0; | |
while (str[i[0]] && !is_separator(str[i[0]], charset)) | |
{ | |
splits[i[1]][i[2]] = str[i[0]]; | |
i[0]++; | |
i[2]++; | |
} | |
splits[i[1]][i[2]] = '\0'; | |
i[1]++; | |
} | |
} | |
splits[i[1]] = NULL; | |
return (splits); | |
} | |
char **ft_split(char *str, char *charset) | |
{ | |
char **splits; | |
int i[3]; | |
i[1] = -1; | |
i[2] = -1; | |
splits = malloc((substring_count(str, charset) + 1) * sizeof(char *)); | |
if (!str || !splits) | |
return (NULL); | |
while (str[++i[1]]) | |
{ | |
i[0] = 0; | |
if (!is_separator(str[i[1]], charset)) | |
{ | |
i[2]++; | |
while (str[i[1]] && !is_separator(str[i[1]], charset)) | |
{ | |
i[0]++; | |
i[1]++; | |
} | |
splits[i[2]] = malloc(i[0] + 1); | |
if (!splits[i[2]]) | |
return (free_previous(splits)); | |
} | |
} | |
return (fill_splits(splits, str, charset)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment