This repository has been archived by the owner on Nov 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathft_split.c
136 lines (123 loc) · 2.67 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcombeau <mcombeau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/27 17:56:03 by mcombeau #+# #+# */
/* Updated: 2021/12/08 12:14:01 by mcombeau ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
DESCRIPTION :
The function ft_split allocates and copies an array of strings by
splitting the given string s using the given separator c.
RETURN VALUE :
An array of strings resulting from the split. NULL if the memory
allocation fails.
*/
static int ft_count_words(const char *s, char c)
{
int words;
int i;
words = 0;
i = 0;
while (s[i])
{
if (i == 0 && s[i] != c)
words++;
if (i > 0 && s[i] != c && s[i - 1] == c)
words++;
i++;
}
return (words);
}
static char **ft_malloc_strs(char **strs, const char *s, char c)
{
int count;
int i;
int x;
count = 0;
i = 0;
x = 0;
while (s[i])
{
if (s[i] != c)
count++;
if ((s[i] == c && i > 0 && s[i - 1] != c)
|| (s[i] != c && s[i + 1] == '\0'))
{
strs[x] = malloc(sizeof(char) * (count + 1));
if (!strs[x])
return (NULL);
count = 0;
x++;
}
i++;
}
return (strs);
}
static char **ft_cpy_strs(char **strs, const char *s, char c)
{
int i;
int x;
int y;
i = 0;
x = 0;
y = 0;
while (s[i])
{
if (s[i] != c)
strs[x][y++] = s[i];
if (s[i] != c && s[i + 1] == '\0')
strs[x][y] = '\0';
if (s[i] == c && i > 0 && s[i - 1] != c)
{
strs[x][y] = '\0';
x++;
y = 0;
}
i++;
}
return (strs);
}
static char **ft_merror(char **strs)
{
int i;
i = 0;
while (strs[i])
{
free(strs[i]);
strs[i] = NULL;
i++;
}
free(strs);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **strs;
int wordcount;
if (!s)
{
strs = malloc(sizeof(char) * 1);
if (!strs)
return (NULL);
*strs = NULL;
return (strs);
}
wordcount = ft_count_words(s, c);
strs = malloc(sizeof(*strs) * (wordcount + 1));
if (!strs)
return (NULL);
if (ft_malloc_strs(strs, s, c))
{
ft_cpy_strs(strs, s, c);
strs[wordcount] = NULL;
}
else
strs = ft_merror(strs);
return (strs);
}