-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
89 lines (80 loc) · 1.9 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebabaogl <ebabaogl@student.42kocaeli.co +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/16 10:06:40 by ebabaogl #+# #+# */
/* Updated: 2024/10/17 22:16:42 by ebabaogl ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static int str_count(char const *str, char sep)
{
int count;
int i;
count = 0;
i = 0;
while (str[i])
{
if (str[i] != sep && (str[i + 1] == sep || !str[i + 1]))
count++;
i++;
}
return (count);
}
static char *str_parse(const char *str, char sep)
{
char *s;
int len;
len = 0;
while (str[len] && str[len] != sep)
len++;
s = (char *)malloc(sizeof(char) * (len + 1));
if (!s)
return (NULL);
ft_memcpy(s, str, len);
s[len] = '\0';
return (s);
}
static void *free_all(char **arr)
{
int i;
i = 0;
while (arr[i])
{
free(arr[i]);
i++;
}
free(arr);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **arr;
char **start;
if (!s)
return (NULL);
arr = (char **)malloc(sizeof(char *) * (str_count(s, c) + 1));
if (!arr)
return (NULL);
start = arr;
while (*s)
{
while (*s && *s == c)
s++;
if (*s)
{
*arr = str_parse(s, c);
if (!*arr)
return (free_all(start));
arr++;
}
while (*s && *s != c)
s++;
}
*arr = NULL;
return (start);
}