-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_string.c
More file actions
46 lines (39 loc) · 775 Bytes
/
Copy pathsplit_string.c
File metadata and controls
46 lines (39 loc) · 775 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
#include "main.h"
/**
* split_string - create an array filled with pointers to each word
* @str: string to split
* @sep: separator to split the string
* Return: An array like argv
*/
char **split_string(char *str, const char *sep)
{
int i = 0, j = 0, word_num = 1;
char *token;
char **arg;
char charsep = sep[0];
if (str == NULL)
return (NULL);
if (str[0] == charsep)
word_num = 0;
while (str[i])
{
if (str[i + 1] != '\0')
{
if (str[i] == charsep && str[i + 1] != charsep)
word_num++;
}
i++;
}
arg = malloc(sizeof(char *) * (word_num + 1));
if (arg == NULL)
return (NULL);
arg[word_num] = NULL;
token = strtok(str, sep);
while (token != NULL)
{
arg[j] = strdup(token);
j++;
token = strtok(NULL, sep);
}
return (arg);
}