-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
98 lines (89 loc) · 1.98 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ibeliaie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/05/17 13:41:09 by ibeliaie #+# #+# */
/* Updated: 2023/05/25 15:06:17 by ibeliaie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/* word count */
static int wcount(char const *s, char c)
{
int count;
int in_word;
count = 0;
in_word = 0;
while (*s)
{
if (*s == c)
in_word = 0;
else if (in_word == 0)
{
in_word = 1;
count++;
}
s++;
}
return (count);
}
/* word length*/
static int wlen(char const *s, char c)
{
int len;
len = 0;
while (*s && *s != c)
{
len++;
s++;
}
return (len);
}
/* word copy */
static char *wcopy(const char *s, int len)
{
int i;
char *word;
word = (char *)malloc((len + 1) * sizeof(char));
if (!word)
return (NULL);
i = 0;
while (i < len)
{
word[i] = s[i];
i++;
}
word[i] = '\0';
return (word);
}
/* split string into array of strings based on delimiter character*/
char **ft_split(char const *s, char c)
{
int i;
int len;
int count;
char **result;
if (!s)
return (NULL);
count = wcount(s, c);
result = (char **)malloc((count + 1) * sizeof(char *));
if (!result)
return (NULL);
i = 0;
while (*s)
{
if (*s != c)
{
len = wlen(s, c);
result[i++] = wcopy(s, len);
s += len;
}
else
s++;
}
result[i] = NULL;
return (result);
}