-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
119 lines (107 loc) · 2.44 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbishop- <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/12 14:59:14 by mbishop- #+# #+# */
/* Updated: 2021/09/12 14:59:23 by mbishop- ### ########.fr */
/* */
/* ************************************************************************** */
/* Allocates and returns an array of strings obtained by splitting 's' using
** the character 'c' as a delimiter. The array must be ended by a NULL
** pointer. */
#include "libft.h"
static void ft_free2d(char *strs)
{
int i;
i = 0;
while (strs[i] != '\0')
{
free(strs);
i++;
}
free(strs);
}
static int ft_wordcount(char *str, char c)
{
int i;
int word;
i = 0;
word = 0;
while (str[i] != '\0')
{
if (str[i] != c)
{
word++;
while (str[i] != c && str[i] != '\0')
i++;
if (str[i] == '\0')
return (word);
}
i++;
}
return (word);
}
static void ft_strcpy(char *word, char *str, char c, int j)
{
int i;
i = 0;
while (str[j] != '\0' && str[j] == c)
j++;
while (str[j + i] != c && str[j + i] != '\0')
{
word[i] = str[j + i];
i++;
}
word[i] = '\0';
}
static char *ft_stralloc(char *str, char c, int *k)
{
char *word;
int j;
j = *k;
word = NULL;
while (str[*k] != '\0')
{
if (str[*k] != c)
{
while (str[*k] != '\0' && str[*k] != c)
*k += 1;
word = (char *)malloc(sizeof(char) * (*k + 1));
if (word == NULL)
return (NULL);
break ;
}
*k += 1;
}
ft_strcpy(word, str, c, j);
return (word);
}
char **ft_split(char const *str, char c)
{
char **strs;
int i;
int j;
int pos;
if (str == NULL)
return (NULL);
i = 0;
pos = 0;
j = ft_wordcount((char *)str, c);
strs = (char **)malloc(sizeof(char *) * (j + 1));
if (strs == NULL)
return (NULL);
strs[j] = NULL;
while (i < j)
{
strs[i] = ft_stralloc(((char *)str), c, &pos);
if (strs[i] == NULL)
{
ft_free2d(strs[i]);
}
i++;
}
return (strs);
}