diff options
| author | yctct <yctct@yctct.com> | 2026-02-05 11:56:49 +0100 |
|---|---|---|
| committer | yctct <yctct@yctct.com> | 2026-02-05 11:56:49 +0100 |
| commit | 861a36d86e7587c043131228cf3a08afd7bc43ad (patch) | |
| tree | a931df9f1845250c0e93adeda52f139c2f5ee1b0 /ft_split.c | |
Add files, first commit
Diffstat (limited to 'ft_split.c')
| -rw-r--r-- | ft_split.c | 105 |
1 files changed, 105 insertions, 0 deletions
diff --git a/ft_split.c b/ft_split.c new file mode 100644 index 0000000..b5d8a8b --- /dev/null +++ b/ft_split.c @@ -0,0 +1,105 @@ +/* +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); +} + +/* +#include <stdio.h> + +int main(void) +{ + char **b; + int i; + char *s2; + + // char *s= "xxxhelloxxallxxofxyoux"; + s2 = " code 42 "; + // char **a; + // a = ft_split(s, 'x'); + b = ft_split(s2, ' '); + i = 0; + while (b[i]) + { + printf("b[%i]: %s\n", i, b[i]); + free(b[i]); + i++; + } + free(b); +} +*/ |
