-
Notifications
You must be signed in to change notification settings - Fork 1
/
ft_strsplit.c
84 lines (75 loc) · 1.9 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jony <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/30 14:18:12 by mhasan #+# #+# */
/* Updated: 2019/11/04 22:02:47 by jony ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_strcount(char const *s, char c)
{
int i;
int count;
i = 0;
while (s[i] && s[i] == c)
i++;
if (s[i] == '\0')
return (0);
count = 1;
while (s[i])
{
if (s[i] == c && s[i + 1] != c && s[i + 1] != '\0')
count++;
i++;
}
return (count);
}
int ft_letc(char const *s, char c)
{
int i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
char **ft_strsplit(char const *s, char c)
{
char **ptr;
int x;
int y;
if (!s)
return (0);
if (!(ptr = (char **)malloc(sizeof(char *) * (ft_strcount(s, c) + 1))))
return (NULL);
x = -1;
while (*s)
{
while (*s && *s == c)
s++;
if (*s)
{
if (!(ptr[++x] = (char *)malloc(sizeof(char) * (ft_letc(s, c) + 1))))
return (NULL);
y = 0;
while (*s && *s != c)
ptr[x][y++] = *s++;
ptr[x][y] = '\0';
}
}
ptr[++x] = NULL;
return (ptr);
}
int main(void)
{
char *str = "*hello**mahmudul***hasan**";
char **splt;
splt = ft_strsplit(str, '*');
printf("%s", splt[0]);
printf("%s", splt[1]);
printf("%s", splt[2]);
return (0);
}