-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
108 lines (97 loc) · 2.43 KB
/
ft_split.c
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jvico-ga <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/17 20:23:34 by jvico-ga #+# #+# */
/* Updated: 2021/10/02 15:22:56 by jvico-ga ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t len_string(size_t i, char const *s, char c)
{
size_t count;
count = i;
while (s[i] != c && s[i] != '\0')
i++;
return (i - count + 2);
}
static char **total_string(char const *s)
{
char **ptr;
ptr = (char **) malloc (sizeof(char *) * 2);
if (ptr == NULL)
return (NULL);
ptr[0] = (char *) malloc(ft_strlen(s) * sizeof(char));
ft_strlcpy(ptr[0], s, ft_strlen(s) + 1);
ptr[1] = NULL;
return (ptr);
}
static size_t counter(char const *s, char c)
{
size_t count;
size_t i;
count = 0;
i = 0;
if (s[0] != c)
count++;
while (s[i] != '\0')
{
if (s[i] == c)
{
while (s[i + 1] == c)
i++;
count++;
}
i++;
}
if (s[i - 1] != c)
count++;
return (count);
}
static void field(char **ptr, char const *s, char c)
{
size_t i;
size_t count;
i = 0;
count = 0;
if (s[i] != c)
{
ptr[count] = malloc (len_string(i, s, c) * sizeof(char));
ft_strlcpy(ptr[count++], &s[i], len_string(i, s, c) - 1);
}
while (s[++i] != '\0')
{
if (s[i - 1] == c && s[i] != c)
{
ptr[count] = malloc((len_string(i, s, c)) * sizeof(char));
ft_strlcpy(ptr[count++], &s[i], len_string(i, s, c) - 1);
}
}
ptr[count] = NULL;
}
char **ft_split(char const *s, char c)
{
size_t count;
size_t i;
char **ptr;
i = 0;
count = 0;
if (s == NULL || *s == '\0')
{
ptr = malloc (sizeof(char *) * 1);
if (ptr == NULL)
return (NULL);
ptr[0] = NULL;
return (ptr);
}
if (c == '\0')
return (total_string(s));
ptr = malloc (sizeof (char *) * (counter(s, c)));
if (ptr == NULL)
return (NULL);
field(ptr, s, c);
return (ptr);
}