-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
81 lines (73 loc) · 1.88 KB
/
ft_split.c
File metadata and controls
81 lines (73 loc) · 1.88 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aabduvak <aabduvak@42ISTANBUL.COM.TR> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/01/03 11:32:35 by aabduvak #+# #+# */
/* Updated: 2022/01/09 03:07:35 by aabduvak ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_words(char const *str, char c)
{
int count;
int i;
i = 0;
count = 0;
while (str[i])
{
while (str[i] == c)
i++;
if (str[i] != c && str[i])
count++;
while (str[i] != c && str[i])
i++;
}
return (count);
}
static char *ft_create_str(char const *str, char c)
{
int i;
char *ptr;
i = 0;
while (str[i] && str[i] != c)
i++;
ptr = (char *) malloc(sizeof(char) * (i + 1));
if (!ptr)
return (NULL);
ft_strlcpy(ptr, str, i + 1);
return (ptr);
}
static void *ft_free(char **ptr, int i)
{
while (i > 0)
free(ptr[i--]);
free(ptr);
return (NULL);
}
char **ft_split(char const *s, char c)
{
int i;
int leng;
char **ptr;
if (!s)
return (NULL);
leng = ft_count_words(s, c);
ptr = (char **)malloc(sizeof(char *) * (leng + 1));
if (!(ptr))
return (NULL);
i = -1;
while (++i < leng)
{
while (s[0] == c)
s++;
ptr[i] = ft_create_str(s, c);
if (!ptr[i])
return (ft_free(ptr, i));
s = s + ft_strlen(ptr[i]);
}
ptr[i] = 0;
return (ptr);
}