-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-strtow.c
102 lines (82 loc) · 1.81 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
102
#include "main.h"
#include <stdlib.h>
int word_len(char *str);
int count_words(char *str);
char **strtow(char *str);
/**
* word_len - Locates the index marking the end of the
* first word contained within a string.
* @str: The string to be searched.
*
* Return: The index marking the end of the initial word pointed to by str.
*/
int word_len(char *str)
{
int index = 0, len = 0;
while (*(str + index) && *(str + index) != ' ')
{
len++;
index++;
}
return (len);
}
/**
* count_words - Counts the number of words contained within a string.
* @str: The string to be searched.
*
* Return: The number of words contained within str.
*/
int count_words(char *str)
{
int index = 0, words = 0, len = 0;
for (index = 0; *(str + index); index++)
len++;
for (index = 0; index < len; index++)
{
if (*(str + index) != ' ')
{
words++;
index += word_len(str + index);
}
}
return (words);
}
/**
* strtow - Splits a string into words.
* @str: The string to be split.
*
* Return: If str = NULL, str = "", or the function fails - NULL.
* Otherwise - a pointer to an array of strings (words).
*/
char **strtow(char *str)
{
char **strings;
int index = 0, words, w, letters, l;
if (str == NULL || str[0] == '\0')
return (NULL);
words = count_words(str);
if (words == 0)
return (NULL);
strings = malloc(sizeof(char *) * (words + 1));
if (strings == NULL)
return (NULL);
for (w = 0; w < words; w++)
{
while (str[index] == ' ')
index++;
letters = word_len(str + index);
strings[w] = malloc(sizeof(char) * (letters + 1));
if (strings[w] == NULL)
{
for (; w >= 0; w--)
free(strings[w]);
free(strings);
return (NULL);
}
for (l = 0; l < letters; l++)
strings[w][l] = str[index++];
strings[w][l] = '\0';
}
strings[w] = NULL;
return (strings);
}