-
Notifications
You must be signed in to change notification settings - Fork 0
/
split_str.c
46 lines (45 loc) · 899 Bytes
/
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
#include "shell.h"
/**
* split_string - Split a string into tokens using a delimiter.
* @str: The input string to be split.
* @delim: The delimiter for splitting.
* Return: An array of strings representing the tokens.
*/
char **split_string(char *str, char *delim)
{
char *start, *end;
unsigned int index = 0, num_delimiters = 0, count = 0;
char **result;
num_delimiters = count_delimiters(str, delim);
result = malloc(sizeof(char *) * (num_delimiters + 2));
index = 0;
start = str;
end = str;
while (str[index])
{
if (str[index] == delim[0])
{
str[index] = '\0';
result[count] = start;
if (str[index + 1])
{
start = &str[index + 1];
end = &str[index + 1];
count++;
index++;
}
else
{
start = NULL;
break;
}
continue;
}
end++;
index++;
}
if (start)
result[count] = start;
result[count + 1] = NULL;
return (result);
}