-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
84 lines (75 loc) · 2.13 KB
/
Copy pathft_split.c
File metadata and controls
84 lines (75 loc) · 2.13 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebin-ahm <ebin-ahm@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/11/29 13:50:20 by ebin-ahm #+# #+# */
/* Updated: 2025/11/29 15:12:45 by ebin-ahm ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t index;
size_t count;
index = 0;
count = 0;
while (s[index] != '\0')
{
if (s[index] != c
&& (index == 0 || s[index -1] == c))
count++;
index++;
}
return (count);
}
static char **free_split(char **result, size_t word_count)
{
size_t index;
index = 0;
while (index < word_count)
{
free(result[index]);
index++;
}
free(result);
return (NULL);
}
static char **fill_words(char **result, char const *s, char c, size_t w_count)
{
size_t index;
size_t word_index;
size_t start;
index = 0;
word_index = 0;
while (s[index] != '\0' && word_index < w_count)
{
while (s[index] == c)
index++;
if (s[index] == '\0')
break ;
start = index;
while (s[index] != '\0' && s[index] != c)
index++;
result[word_index] = ft_substr(s, start, index - start);
if (!result[word_index])
return (free_split(result, word_index));
word_index++;
}
result[word_index] = NULL;
return (result);
}
char **ft_split(char const *s, char c)
{
char **result;
size_t word_count;
if (!s)
return (NULL);
word_count = count_words(s, c);
result = (char **)malloc((word_count + 1) * sizeof(char *));
if (!result)
return (NULL);
return (fill_words(result, s, c, word_count));
}