-
Notifications
You must be signed in to change notification settings - Fork 4
/
101-strtow.c
67 lines (64 loc) · 1.28 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
#include "main.h"
#include <stdlib.h>
/**
* ch_free_grid - frees a 2 dimensional array.
* @grid: multidimensional array of char.
* @height: height of the array.
*
* Return: no return
*/
void ch_free_grid(char **grid, unsigned int height)
{
if (grid != NULL && height != 0)
{
for (; height > 0; height--)
free(grid[height]);
free(grid[height]);
free(grid);
}
}
/**
* strtow - splits a string into words.
* @str: string.
*
* Return: pointer of an array of integers
*/
char **strtow(char *str)
{
char **aout;
unsigned int c, height, i, j, a1;
if (str == NULL || *str == '\0')
return (NULL);
for (c = height = 0; str[c] != '\0'; c++)
if (str[c] != ' ' && (str[c + 1] == ' ' || str[c + 1] == '\0'))
height++;
aout = malloc((height + 1) * sizeof(char *));
if (aout == NULL || height == 0)
{
free(aout);
return (NULL);
}
for (i = a1 = 0; i < height; i++)
{
for (c = a1; str[c] != '\0'; c++)
{
if (str[c] == ' ')
a1++;
if (str[c] != ' ' && (str[c + 1] == ' ' || str[c + 1] == '\0'))
{
aout[i] = malloc((c - a1 + 2) * sizeof(char));
if (aout[i] == NULL)
{
ch_free_grid(aout, i);
return (NULL);
}
break;
}
}
for (j = 0; a1 <= c; a1++, j++)
aout[i][j] = str[a1];
aout[i][j] = '\0';
}
aout[i] = NULL;
return (aout);
}