-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
110 lines (101 loc) · 2.19 KB
/
ft_split.c
File metadata and controls
110 lines (101 loc) · 2.19 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
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aymohamm <aymohamm@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/05 10:02:40 by aymohamm #+# #+# */
/* Updated: 2023/11/11 10:33:04 by aymohamm ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_substr(char const *s, char c)
{
int count;
int len;
int i;
int j;
i = 0;
len = ft_strlen(s);
j = 0;
count = 0;
while (i < len)
{
while (i < len && s[i] == c)
i++;
j = i;
while (i < len && s[i] != c)
i++;
if (i > j)
count++;
}
return (count);
}
static char *ft_strncpy(char *dest, const char *src, unsigned int n)
{
unsigned int i;
i = 0;
while (src[i] != '\0' && i < n)
{
dest[i] = src[i];
i++;
}
while (i < n)
{
dest[i] = '\0';
i++;
}
return (dest);
}
static void split_substr(char **str, char const *s, char c)
{
int str_i;
int start;
int i;
int len;
i = 0;
start = 0;
str_i = 0;
len = ft_strlen(s);
while (i < len)
{
while (i < len && s[i] == c)
i++;
start = i;
while (i < len && s[i] != c)
i++;
if (i > start)
{
str[str_i] = malloc(i - start + 1);
ft_strncpy(str[str_i], &s[start], i - start);
str[str_i][i - start] = '\0';
str_i++;
}
}
}
char **ft_split(char const *s, char c)
{
char **str;
int count;
int i;
if (!s)
return (NULL);
count = count_substr(s, c);
str = (char **)malloc(sizeof(char *) * (count + 1));
if (!str)
return (NULL);
str[count] = NULL;
i = 0;
split_substr(str, s, c);
while (i > 0)
{
if (str[i] == NULL)
{
free(str[i]);
return (NULL);
}
i--;
}
return (str);
}