-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
91 lines (83 loc) · 2.02 KB
/
ft_split.c
File metadata and controls
91 lines (83 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nvillalt <nvillalt@student.42madrid> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/05 15:06:26 by nvillalt #+# #+# */
/* Updated: 2023/10/06 13:20:16 by nvillalt ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_strings(char const *s, char c)
{
size_t i;
size_t string;
size_t flag;
i = 0;
string = 0;
flag = 0;
while (s[i] == c)
i++;
while (s[i] != 0)
{
if (s[i] != c && flag == 0)
{
flag = 1;
string++;
}
if (s[i] == c)
flag = 0;
i++;
}
return (string);
}
static size_t count_chars(char const *s, char c)
{
size_t counter;
counter = 0;
while (*s != 0 && *s != c)
{
s++;
counter++;
}
return (counter);
}
static char **free_split(char **split, int n)
{
while (n >= 0)
{
free(split[n]);
n--;
}
free(split);
return (0);
}
char **ft_split(char const *s, char c)
{
size_t n_strings;
size_t s_len;
size_t n;
char **result;
if (*s == '\0' || s == NULL)
return ((char **)ft_calloc(sizeof(char *), 1));
n_strings = count_strings(s, c);
result = ft_calloc(sizeof(char *), n_strings + 1);
if (!result)
return (0);
n = 0;
while (n < n_strings)
{
while (*s == c)
s++;
s_len = count_chars(s, c) + 1;
result[n] = ft_calloc(sizeof(char), s_len);
if (!result[n])
return (free_split(result, n));
ft_strlcpy(result[n], s, s_len);
s += s_len;
n++;
}
return (result);
}