-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstr_to_arr.c
84 lines (73 loc) · 1.44 KB
/
str_to_arr.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "main.h"
/**
* arr_size - Finds the size of the array needed for
* the str_to_arr function
* @string: Original string to be split.
* @delim: Delimiter used to split the string.
*
* Return: Pointer to the array of strings.
*/
int arr_size(char *string, char *delim)
{
char *str = NULL, *temp = NULL;
int size = 0;
str = _strdup(string);
if (str == NULL)
return (-1);
/* str used to count the size of the array */
temp = strtok(str, delim);
while (temp)
{
size++;
temp = strtok(NULL, delim);
}
free(str);
return (size);
}
/**
* str_to_arr - Converts an input string to an array of strings
* based on a specified delimiter.
* @string: Original string to be split.
* @delim: Delimiter used to split the string.
*
* Return: Pointer to the array of strings.
*/
char **str_to_arr(char *string, char *delim)
{
char **argv = NULL;
char *str = NULL, *temp = NULL;
int i = 0;
int size = arr_size(string, delim);
if (string == NULL || delim == NULL)
return (NULL);
str = _strdup(string);
if (str == NULL)
return (NULL);
argv = malloc(sizeof(char *) * (size + 1));
if (argv == NULL)
{
free(str);
return (NULL);
}
temp = strtok(str, delim);
while (temp)
{
int j;
argv[i] = _strdup(temp);
if (argv[i] == NULL)
{
for (j = 0; j < i; j++)
{
free(argv[j]);
free(argv);
free(str);
}
return (NULL);
}
temp = strtok(NULL, delim);
i++;
}
argv[i] = NULL;
free(str);
return (argv);
}