-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
66 lines (61 loc) · 1.77 KB
/
ft_split.c
File metadata and controls
66 lines (61 loc) · 1.77 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pix <pix@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/27 22:01:09 by stales #+# #+# */
/* Updated: 2022/04/04 02:58:51 by pix ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
/**
* @brief Split string s with c as separator
*
* @param c Character as separator
* @param s String to return
*
* @return (char **)Allocated list of separated string, termined by NULL char
*/
char *init_str(char *s, char c)
{
int i;
char *ptr;
i = 0;
while (s[i] && s[i] != c)
i++;
ptr = (char *)malloc(sizeof(char) * (i + 1));
if (!ptr)
return (NULL);
ft_strlcpy(ptr, s, i + 1);
return (ptr);
}
char **ft_split(char *s, char c)
{
int i[2];
char **ptr;
if (!s)
return (NULL);
i[1] = ft_get_words(s, c);
ptr = (char **)malloc(sizeof(char *) * (i[1] + 1));
i[0] = -1;
while (ptr && ++i[0] < i[1])
{
while (s[0] == c)
s++;
ptr[i[0]] = init_str(s, c);
if (!ptr[i[0]])
{
while (i[0] > 0)
free(ptr[i[0]--]);
free(ptr);
return (NULL);
}
s = s + ft_strlen(ptr[i[0]]);
}
if (ptr)
ptr[i[0]] = 0;
return (ptr);
}