-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_strsplit.c
More file actions
90 lines (82 loc) · 1.98 KB
/
ft_strsplit.c
File metadata and controls
90 lines (82 loc) · 1.98 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
86
87
88
89
90
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nparker <nparker@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/07 16:54:02 by nparker #+# #+# */
/* Updated: 2018/12/14 15:37:29 by nparker ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void ft_free2dmass(char **res, int i)
{
while (i >= 0)
{
free(res[i]);
res[i] = NULL;
i--;
}
free(res);
res = NULL;
}
static int ft_word_len(char const *str, char c)
{
size_t i;
size_t len;
i = 0;
len = 0;
while (str[i] == c)
i++;
while (str[i] != c && str[i] != '\0')
{
i++;
len++;
}
return (len);
}
static int ft_word_count(char const *str, char c)
{
size_t count;
size_t i;
i = 0;
count = 0;
while (str[i])
{
while (str[i] == c)
i++;
if (str[i] != c && str[i] != '\0')
count++;
while (str[i] != c && str[i] != '\0')
i++;
}
return (count);
}
char **ft_strsplit(char const *s, char c)
{
int i;
size_t j;
size_t k;
char **arr;
i = -1;
j = 0;
if (!s || !c)
return (0);
arr = (char**)malloc(sizeof(arr) * (ft_word_count(s, c) + 1));
if (!arr)
return (0);
while (++i < ft_word_count(s, c))
{
k = 0;
if (!(arr[i] = ft_strnew(ft_word_len(&s[j], c))))
ft_free2dmass(arr, i);
while (s[j] == c)
j++;
while (s[j] != c && s[j])
arr[i][k++] = s[j++];
arr[i][k] = '\0';
}
arr[i] = 0;
return (arr);
}