-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
106 lines (96 loc) · 2.33 KB
/
ft_split.c
File metadata and controls
106 lines (96 loc) · 2.33 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split.c :+: :+: */
/* +:+ */
/* By: pzlatov <pzlatov@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2024/10/24 14:08:14 by pzlatov #+# #+# */
/* Updated: 2024/10/25 20:07:35 by pzlatov ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(const char *s, char c)
{
size_t i;
size_t count;
if (!s)
return (0);
i = 0;
count = 0;
while (s[i] != '\0')
{
while (s[i] == c && s[i] != '\0')
i++;
if (s[i] != '\0')
{
count++;
while (s[i] != '\0' && s[i] != c)
i++;
}
}
return (count);
}
static void free_words(char **strings, size_t word)
{
size_t i;
i = 0;
while (i < word)
{
free (strings[i]);
i++;
}
free (strings);
}
static char *next_word(const char *s, char c, size_t *let)
{
size_t start;
size_t word_len;
while (s[*let] == c && s[*let] != '\0')
(*let)++;
start = *let;
word_len = 0;
while (s[*let] != '\0' && s[*let] != c)
{
(*let)++;
word_len++;
}
return (ft_substr(s, start, word_len));
}
char **ft_split(char const *s, char c)
{
size_t let;
size_t word;
char **strings;
word = 0;
let = 0;
strings = malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!strings || !s)
return (NULL);
while (word < count_words(s, c))
{
strings[word] = next_word(s, c, &let);
if (!strings[word])
{
free_words (strings, word);
return (NULL);
}
if (strings[word][0] != '\0')
word++;
}
strings[word] = NULL;
return (strings);
}
// int main()
// {
// char str[] = " I am a genius";
// char sep = ' ';
// char **arr = ft_split(str, sep);
// for (int i = 0; arr[i] != NULL; i++)
// {
// printf("Word %d: %s\n", i + 1, arr[i]);
// free(arr[i]);
// }
// free(arr);
// return (0);
// }