-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokensplit.c
44 lines (42 loc) · 868 Bytes
/
tokensplit.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
#include "holberton.h"
/**
*tokensplit - splits a line into tokens and stores into a char array
*@line: the line string to split
*
*Return: the array of strings
*/
char **tokensplit(char *line)
{
int i = 0;
int tokencount = 0;
char **tokenarray;
char *token, *tokencopy;
if (line == NULL)
return (NULL);
while (*(line + i) != '\0')
{
if (line[i] != ' ' && (line[i + 1] == ' ' || line[i + 1] == '\0'
|| line[i + 1] == '\t'))
tokencount++;
i++;
}
i = 0;
tokenarray = malloc(sizeof(char *) * (tokencount + 1));
if (tokenarray == NULL)
return (NULL);
token = strtok(line, DELIMS);
while (token != NULL)
{
tokencopy = _strdup(token);
if (tokencopy == NULL)
{
free(tokenarray);
return (NULL);
}
*(tokenarray + i) = tokencopy;
token = strtok(NULL, DELIMS);
i++;
}
*(tokenarray + i) = NULL;
return (tokenarray);
}