-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-strtow.c
79 lines (67 loc) · 1.14 KB
/
101-strtow.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdlib.h>
#include "main.h"
/**
* count - helper function to count the number of words in a string
* @str: string to evaluate
*
* Return: number of words
*/
int count(char *str)
{
int f, c, w;
f = 0;
w = 0;
for (c = 0; str[c] != '\0'; c++)
{
if (str[c] == ' ')
f = 0;
else if (f == 0)
{
f = 1;
w++;
}
}
return (w);
}
/**
* **strtow - splits a string into words
* @str: string to split
*
* Return: pointer to an array of strings or NULL
*/
char **strtow(char *str)
{
char **array, *tmp;
int i, k = 0, len = 0, words, c = 0, start, end;
while (*(str + len))
len++;
words = count(str);
if (words == 0)
return (NULL);
array = (char **) malloc(sizeof(char *) * (words + 1));
if (array == NULL)
return (NULL);
for (i = 0; i <= len; i++)
{
if (str[i] == ' ' || str[i] == '\0')
{
if (c)
{
end = i;
tmp = (char *) malloc(sizeof(char) * (c + 1));
if (tmp == NULL)
return (NULL);
while (start < end)
*tmp++ = str[start++];
*tmp = '\0';
array[k] = tmp - c;
k++;
c = 0;
}
}
else if (c++ == 0)
start = i;
}
array[k] = NULL;
return (array);
}