diff options
| author | yctct <yctct@yctct.com> | 2026-04-16 18:25:12 +0200 |
|---|---|---|
| committer | yctct <yctct@yctct.com> | 2026-04-16 18:25:12 +0200 |
| commit | 40ad9bfe202f72a5b52eed8ff38da9b27de12adb (patch) | |
| tree | 3191366496651b9b4cbb213aec0966f24984333a /lib/ft_split.c | |
Diffstat (limited to 'lib/ft_split.c')
| -rw-r--r-- | lib/ft_split.c | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/lib/ft_split.c b/lib/ft_split.c new file mode 100644 index 0000000..af73f73 --- /dev/null +++ b/lib/ft_split.c @@ -0,0 +1,81 @@ +/* +Libft Copyright (C) 2026 yctct + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ + +#include "libft.h" + +static int ft_countword(char const *s, char c) +{ + int i; + int wordcounter; + + i = 0; + wordcounter = 0; + while (s[i]) + { + if (s[i] == c) + i++; + else + { + wordcounter++; + while (s[i] != c && s[i]) + i++; + } + } + return (wordcounter); +} + +static char **ft_addwords(char **a, char const *s, char c, int wordcounter) +{ + int i; + int start; + int word; + + i = 0; + word = 0; + while (wordcounter--) + { + while (s[i] == c) + i++; + start = i; + while (s[i] != c && s[i] != 0) + i++; + a[word] = ft_substr(s, start, i - start); + if (!a[word]) + { + while (word-- >= 0) + free(a[word]); + return (free(a), NULL); + } + word++; + i++; + } + return (a[word] = 0, a); +} + +char **ft_split(char const *s, char c) +{ + char **a; + int wordcounter; + + wordcounter = ft_countword(s, c); + a = malloc(sizeof(a) * (wordcounter + 1)); + if (!a) + return (NULL); + a = ft_addwords(a, s, c, wordcounter); + return (a); +} + |
