-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path101-strtow.c
74 lines (70 loc) · 1.17 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
#include "holberton.h"
#include <stdlib.h>
/**
* wrdcnt - counts the number of words in a string
* @s: string to count
* Return: int of number of words
**/
int wrdcnt(char *s)
{
int i, n = 0;
for (i = 0; s[i]; i++)
{
if (s[i] == ' ')
{
if (s[i + 1] != ' ' && s[i + 1] != '\0')
n++;
}
else if (i == 0)
n++;
}
n++;
return (n);
}
/**
* strtow - splits a string into words
* @str: string to split
* Return: pointer to an array of strings
**/
char **strtow(char *str)
{
int i, j, k, l, n = 0, wc = 0;
char **w;
if (str == NULL || *str == '\0')
return (NULL);
n = wrdcnt(str);
if (n == 1)
return (NULL);
w = (char **)malloc(n * sizeof(char *));
if (w == NULL)
return (NULL);
w[n - 1] = NULL;
i = 0;
while (str[i])
{
if (str[i] != ' ' && (i == 0 || str[i - 1] == ' '))
{
for (j = 1; str[i + j] != ' ' && str[i + j]; j++)
;
j++;
w[wc] = (char *)malloc(j * sizeof(char));
j--;
if (w[wc] == NULL)
{
for (k = 0; k < wc; k++)
free(w[k]);
free(w[n - 1]);
free(w);
return (NULL);
}
for (l = 0; l < j; l++)
w[wc][l] = str[i + l];
w[wc][l] = '\0';
wc++;
i += j;
}
else
i++;
}
return (w);
}