-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
85 lines (76 loc) · 1.83 KB
/
ft_split.c
File metadata and controls
85 lines (76 loc) · 1.83 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
82
83
84
85
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aycami <aycami@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/07 14:56:29 by aycami #+# #+# */
/* Updated: 2024/10/07 14:56:37 by aycami ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static unsigned int ft_wordcount(const char *s, char c)
{
unsigned int word;
word = 0;
while (*s)
{
if (*s == c)
s++;
else
{
while (*s != c && *s)
s++;
word++;
}
}
return (word);
}
static unsigned int ft_index(const char *s, char c)
{
unsigned int i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
static char **ft_free(char **result)
{
int i;
i = 0;
while (result[i])
{
free(result[i]);
i++;
}
free(result);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **str;
unsigned int j;
unsigned int a;
str = (char **)malloc((ft_wordcount(s, c) + 1) * sizeof(char *));
if (!str)
return (NULL);
a = -1;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
str[++a] = (char *)malloc((ft_index(s, c) + 1) * sizeof(char));
if (!str[a])
return (ft_free(str));
j = 0;
while (*s && *s != c)
str[a][j++] = *s++;
str[a][j] = '\0';
}
}
str[++a] = NULL;
return (str);
}