-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenize_str_to_array.c
More file actions
46 lines (36 loc) · 844 Bytes
/
tokenize_str_to_array.c
File metadata and controls
46 lines (36 loc) · 844 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 "shell.h"
/**
* tokenize_str_to_array - converts string to array
* @str: string
* Return: a pointer to a char array containing the converted text
*/
char **tokenize_str_to_array(char *str)
{
unsigned int count_chars;
char **cmd_lines;
char *cmd, *token;
int n;
cmd_lines = NULL;
n = 0;
count_chars = 0;
count_chars = count_chars_in_str(str, '\n');
/* memory allocation */
cmd_lines = (char **)malloc((count_chars + 1) * sizeof(char *));
/* input str is tokenized with delimiter set to newline */
token = _strtok(str, "\n");
/* first token (command) is duplicated */
cmd = _strdup(token);
cmd_lines[n++] = cmd;
while (token != NULL)
{
token = _strtok(NULL, "\n");
if (token != NULL)
{
cmd = _strdup(token);
cmd_lines[n++] = cmd;
}
}
free(str);
cmd_lines[n] = NULL;
return (cmd_lines);
}