-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_strtokr.c
More file actions
53 lines (48 loc) · 1002 Bytes
/
_strtokr.c
File metadata and controls
53 lines (48 loc) · 1002 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
#include "shell.h"
/**
* _strtokr - A function that tokenizes input gotten using read.
* @str: token to tokenize.
* @delim: the delimeter.
*
* Return: The tokenize strings.
*/
char **_strtokr(char *str, char *delim)
{
char **strings = NULL;
int num_tokens = 0, i = 0, j = 0;
char *token, *pos, *copy = NULL;
if (!str || !delim)
return (NULL);
copy = strdup(str);
if (!copy)
exit(EXIT_FAILURE);
token = strtok(copy, delim);
while (token != NULL)
{
num_tokens++;
token = strtok(NULL, delim);
}
free(copy);
strings = malloc(sizeof(char *) * (num_tokens + 1));
if (!strings)
exit(EXIT_FAILURE);
pos = str;
while ((token = strtok(pos, delim)) != NULL)
{
if (*token != '\0')
{
strings[i] = strdup(token);
if (!strings[i])
{
for (j = 0; j < i; j++)
free(strings[j]);
free(strings);
exit(EXIT_FAILURE);
}
i++;
}
pos = NULL; /* Set pos to NULL to continue tokenizing the original string */
}
strings[i] = NULL;
return (strings);
}