-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsplit.c
More file actions
59 lines (54 loc) · 987 Bytes
/
split.c
File metadata and controls
59 lines (54 loc) · 987 Bytes
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
#include "shell.h"
#include <stddef.h>
/**
* str_split - split a string into tokens by delimeter
* @str: string
* @del: delimeter
* Return: array of strings of tokens
**/
char **str_split(const char *str, const char del)
{
char **s = NULL;
int i = 0, j, w = 0;
while (str[i] != '\0' && str[i] == del)
i++;
if (!str[i])
return (NULL);
i = 0;
while (str[i])
{
j = i;
if (str[i] != del)
{
s = _realloc(s, sizeof(char *) * w,
sizeof(char *) * (w + 1));
s[w] = NULL;
while (str[j] && str[j] != del)
{
s[w] = _realloc(s[w], (j - i), ((j - i) + 1));
s[w][j - i] = str[j];
j++;
}
s[w] = _realloc(s[w], (j - i), ((j - i) + 1));
s[w][j - i] = '\0';
i += (j - i);
w++;
}
else
i++;
}
s = _realloc(s, sizeof(char *) * w, sizeof(char *) * (w + 1));
s[w] = NULL;
return (s);
}
/**
* free_arr - free the array
* @arr: array
**/
void free_arr(char **arr)
{
int i = 0;
while (arr[i])
free(arr[i++]);
free(arr);
}