-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_strsplit.c
More file actions
83 lines (74 loc) · 1.87 KB
/
Copy pathft_strsplit.c
File metadata and controls
83 lines (74 loc) · 1.87 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bekim <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/18 20:13:57 by bekim #+# #+# */
/* Updated: 2020/03/07 13:15:36 by bekim ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_strings(char const *str, char c)
{
int count;
count = 0;
while (*str)
{
while (*str == c)
str++;
if (*str)
count++;
while (*str != c && *str)
str++;
}
return (count);
}
static int str_len(char const *str, char c)
{
int size;
size = 0;
while (*str != c && *str)
{
size++;
str++;
}
return (size);
}
static char *create_word(char const *str, int len)
{
char *word;
word = ft_strnew(len);
if (word == NULL)
return (NULL);
ft_strncpy(word, str, len);
return (word);
}
char **ft_strsplit(char const *s, char c)
{
char **ret;
int size;
int index;
char *word;
if (!s)
return (NULL);
index = -1;
size = count_strings(s, c);
ret = (char **)malloc(sizeof(char*) * (size + 1));
if (ret == NULL)
return (NULL);
while (++index < size)
{
while (*s == c)
s++;
word = create_word(s, str_len(s, c));
if (word == NULL)
return (NULL);
ret[index] = word;
while (*s != c && *s)
s++;
}
ret[index] = 0;
return (ret);
}