Repository navigation
Expand file tree
/
Copy pathsplit.c
More file actions
88 lines (81 loc) · 2.11 KB
/
Copy pathsplit.c
File metadata and controls
88 lines (81 loc) · 2.11 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hceviz <hceviz@student.42warsaw.pl> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/02/22 13:54:09 by hceviz #+# #+# */
/* Updated: 2025/02/24 09:25:49 by hceviz ### ########.fr */
/* */
/* ************************************************************************** */
#include "pushswap.h"
int count_words(char *s, char c)
{
int count;
bool inside_word;
count = 0;
while (*s)
{
inside_word = false;
while (*s == c)
++s;
while (*s != c && *s)
{
if (!inside_word)
{
++count;
inside_word = true;
}
++s;
}
}
return (count);
}
char *get_next_word(char *s, char c)
{
static int cursor = 0;
char *next_word;
int len;
int i;
len = 0;
i = 0;
while (s[cursor] == c)
++cursor;
while ((s[cursor + len] != c) && s[cursor + len])
++len;
next_word = malloc((size_t)len * sizeof(char) + 1);
if (!next_word)
return (NULL);
while ((s[cursor] != c) && s[cursor])
next_word[i++] = s[cursor++];
next_word[i] = '\0';
return (next_word);
}
char **split(char *s, char c)
{
int words_count;
char **result_array;
int i;
i = 0;
words_count = count_words(s, c);
if (!words_count)
exit(1);
result_array = malloc(sizeof(char *) * (size_t)(words_count + 2));
if (!result_array)
return (NULL);
while (words_count-- >= 0)
{
if (i == 0)
{
result_array[i] = malloc(sizeof(char));
if (!result_array[i])
return (NULL);
result_array[i++][0] = '\0';
continue ;
}
result_array[i++] = get_next_word(s, c);
}
result_array[i] = NULL;
return (result_array);
}