-
Notifications
You must be signed in to change notification settings - Fork 0
/
split_str.c
57 lines (55 loc) · 1.45 KB
/
split_str.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
#include "shell.h"
/**
* split_str - Tokenizes a string into an array of strings.
*
* @line: The string to be tokenized.
* Return: An array of strings (tokens).
* Returns NULL on failure or when @line is NULL.
*/
char **split_str(char *line)
{
char *token, *delim = " \t\n", *tmp = NULL, **command = NULL;
int count = 0, i = 0;
/* Check if the input string is NULL*/
if (!line)
return (NULL);
/*Duplicate the input string to avoid modifying the original*/
tmp = my_strdup(line);
/*Tokenize the duplicated string to count the number of tokens*/
token = strtok(tmp, delim);
if (token == NULL)
{
/*Free allocated memory and set pointers to NULL*/
free(line), line = NULL;
free(tmp), tmp = NULL;
return (NULL);
}
while (token)
{
count++;
token = strtok(NULL, delim);
}
/*Free the duplicated string*/
free(tmp), tmp = NULL;
/*Allocate memory for the array of strings (tokens)*/
command = malloc(sizeof(char *) * (count + 1));
if (!command)
{
/*Free original line and return NULL in case of memory allocation failure*/
free(line), line = NULL;
return (NULL);
}
/*Tokenize the original string and copy tokens to the array*/
token = strtok(line, delim);
while (token)
{
command[i] = my_strdup(token);
token = strtok(NULL, delim);
i++;
}
/*Free the original line and set the last element of the array to NULL*/
free(line), line = NULL;
command[i] = NULL;
/* Return the array of strings (tokens)*/
return (command);
}