-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstring_toknize.c
69 lines (63 loc) · 1.2 KB
/
string_toknize.c
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
#include "shell.h"
/**
* string_tok - a function that tokinize an array of strings
* @strings: string to be tokinized
* @delim: delimeter
* Return: array of tokinized string
*/
char **string_tok(char *strings, char *delim)
{
char *token = NULL, *string_cpy = NULL;
char **args = NULL;
int num_token = 0, i = 0;
string_cpy = _strdup(strings);
if (string_cpy == NULL)
return (NULL);
token = strtok(string_cpy, delim);
while (token)
{
num_token++;
token = strtok(NULL, delim);
}
num_token++;
args = malloc(sizeof(char *) * num_token);
if (args == NULL)
{
free(string_cpy);
return (NULL);
}
token = NULL;
token = strtok(strings, delim);
i = 0;
while (token)
{
args[i] = malloc(sizeof(char) * (_strlen(token) + 1));
if (args[i] == NULL)
{
free_args(args, i);
free(string_cpy);
return (NULL);
}
str_cpy(args[i], token);
token = strtok(NULL, delim);
i++;
}
args[i] = NULL;
free(string_cpy);
return (args);
}
/**
* free_args - function that free args allocated space
* @args: memory allocated
* @count: number of allocated memory
* Return: null
*/
void free_args(char **args, int count)
{
int i;
for (i = 0; i < count; i++)
{
free(args[i]);
}
free(args);
}