-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy path101-strtow.c
101 lines (92 loc) · 1.38 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "main.h"
/**
*strtow - splits a stirng into words
*@str: string to be splitted
*
*Return: pointer to the array of splitted words
*/
char **strtow(char *str)
{
char **split;
int i, j = 0, temp = 0, size = 0, words = num_words(str);
if (words == 0)
return (NULL);
split = (char **) malloc(sizeof(char *) * (words + 1));
if (split != NULL)
{
for (i = 0; i <= len(str) && words; i++)
{
if ((str[i] != ' ') && (str[i] != '\0'))
size++;
else if (((str[i] == ' ') || (str[i] == '\0')) && i && (str[i - 1] != ' '))
{
split[j] = (char *) malloc(sizeof(char) * size + 1);
if (split[j] != NULL)
{
while (temp < size)
{
split[j][temp] = str[(i - size) +temp];
temp++;
}
split[j][temp] = '\0';
size = temp = 0;
j++;
}
else
{
while (j-- >= 0)
free(split[j]);
free(split);
return (NULL);
}
}
}
split[words] = NULL;
return (split);
}
else
return (NULL);
}
/**
* num_words - counts the number of words in str
*@str: string to be used
*
*Return: number of words
*/
int num_words(char *str)
{
int i = 0, words = 0;
while (i <= len(str))
{
if ((str[i] != ' ') && (str[i] != '\0'))
{
i++;
}
else if (((str[i] == ' ') || (str[i] == '\0')) && i && (str[i - 1] != ' '))
{
words += 1;
i++;
}
else
{
i++;
}
}
return (words);
}
/**
* len - returns length of str
*@str: string to be counted
*
* Return: length of the string
*/
int len(char *str)
{
int len = 0;
if (str != NULL)
{
while (str[len])
len++;
}
return (len);
}