-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
85 lines (77 loc) · 2.03 KB
/
ft_strsplit.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mwilliam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/03 17:09:09 by mwilliam #+# #+# */
/* Updated: 2016/12/03 17:09:10 by mwilliam ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Returns an array of "fresh" strings by splitting s using c as a delimiter
*/
static int ft_countwords(char const *s, char c)
{
int index;
int count;
index = 0;
count = 0;
while (s[index])
{
while (s[index] == c)
index++;
if (s[index] != c && s[index] != '\0')
count++;
while (s[index] != c && s[index] != '\0')
index++;
}
return (count);
}
static int ft_wordlength(char const *s, char c)
{
int index;
int count;
index = 0;
count = 0;
while (s[index])
{
while (s[index] == c)
index++;
while (s[index] != c && s[index] != '\0')
{
index++;
count++;
}
}
return (count);
}
char **ft_strsplit(char const *s, char c)
{
int index;
int m;
int n;
char **str;
index = 0;
m = 0;
if (!s || !(str = (char **)malloc(sizeof(char *) *
(ft_countwords(s, c) + 1))))
return (NULL);
while (index < ft_countwords(s, c))
{
n = 0;
if (!(str[index] = (char *)malloc(sizeof(char) * ft_wordlength(s, c)
+ 1)))
str[index] = NULL;
while (s[m] == c && s[m])
m++;
while (s[m] != c && s[m])
str[index][n++] = s[m++];
str[index][n] = '\0';
index++;
}
str[index] = NULL;
return (str);
}