-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
98 lines (90 loc) · 2.23 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hcastanh <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/14 18:48:28 by pde-carv #+# #+# */
/* Updated: 2020/05/15 13:14:30 by hcastanh ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Description
** -----------
** Parse a string searching for a delimiter and split the string,
** in an array containing the found strings.
**
** Parameters
** ----------
** char const *s: the string to split.
** char c: the char to be used as delimiter.
**
** Returns
** -------
** An array of the strings resulted from the split.
** NULL in case the allocation fails.
*/
int count_words(const char *s, char c)
{
int i;
int words;
i = 0;
words = 0;
while (s[i] != '\0')
{
if (s[i] != c && i == 0)
words++;
else if (s[i] == c && s[i + 1] != c && s[i + 1] != '\0')
words++;
i++;
}
return (words);
}
char *ft_getfields(int *a, const char *s, char c)
{
char *field;
int j;
int i;
i = *a;
field = NULL;
while (s[i] == c)
i++;
j = i;
while (s[i] && s[i] != c)
i++;
if (!(field = (char *)malloc((i - j + 1) * sizeof(char))))
return (NULL);
i = j;
while (s[i] && s[i] != c)
{
field[i - j] = s[i];
i++;
}
field[i - j] = '\0';
while (s[i] && s[i] == c)
i++;
return (field);
}
char **ft_split(const char *s, char c)
{
int i;
int k;
char **split;
int words;
if (!s)
return (NULL);
words = count_words(s, c);
if (!(split = (char **)malloc((words + 1) * sizeof(char *))))
return (NULL);
i = 0;
k = 0;
while (k < words)
{
split[k] = ft_getfields(&i, s, c);
k++;
}
split[k] = NULL;
return (split);
}