-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split_pipex.c
105 lines (94 loc) · 2.34 KB
/
ft_split_pipex.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split_pipex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dvan-der <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/14 13:55:25 by dvan-der #+# #+# */
/* Updated: 2021/12/14 13:55:27 by dvan-der ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
static void free_splitted_arr(char **split_arr)
{
size_t i;
i = 0;
while (split_arr[i])
{
free(split_arr[i]);
i++;
}
}
static int count_str(const char *s, char c, int hor_i)
{
size_t i;
i = 0;
while (s[hor_i] != c && s[hor_i] != '\0')
{
hor_i++;
i++;
}
return (i);
}
static char **fill_spl_arr(char **split_arr, int splits, const char *s, int c)
{
int hor_i;
int vert_i;
int length;
hor_i = 0;
vert_i = 0;
length = 0;
while (vert_i < splits - 1)
{
while (s[hor_i] == c)
hor_i++;
length = count_str(s, c, hor_i);
split_arr[vert_i] = (char *)ft_calloc(length + 1, sizeof(char));
if (!split_arr)
return (NULL);
ft_strlcpy(split_arr[vert_i], &s[hor_i], length + 1);
hor_i += length;
vert_i++;
}
split_arr[vert_i] = NULL;
return (split_arr);
}
static int ft_count_splits_pipex(char const *s, char c)
{
int counter;
int len;
int i;
counter = 0;
len = ft_strlen(s);
i = 0;
while (i < len)
{
if (s[i] != c)
counter++;
while (s[i] != c && i < len)
i++;
i++;
}
return (counter + 1);
}
char **ft_split_pipex(char const *s, char c)
{
char **split_arr;
int splits;
if (!s)
return (NULL);
splits = ft_count_splits_pipex(s, c);
split_arr = (char **)ft_calloc(splits + 1, sizeof(char *));
if (!split_arr)
return (NULL);
if (!*s || splits == 0)
return (split_arr);
if (!fill_spl_arr(split_arr, splits, s, c))
{
free_splitted_arr(split_arr);
free(split_arr);
return (NULL);
}
return (split_arr);
}