-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-strtow.c
74 lines (71 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 "main.h"
#include <stdlib.h>
#include <stdio.h>
/**
* word_len - calculate length of word
* @s: string
*
* Return: length
*/
int word_len(char *s)
{
int length = 0;
for (; *s != ' ' && *s != '\0'; s++)
length++;
return (length);
}
/**
* number_words - count the number of words in a string
* @s: string
*
* Return: number of words
*/
int number_words(char *s)
{
int nb = 0;
char *tmp;
tmp = s;
for (; *s; s++)
{
if (*s != ' ' && (*(s + 1) == ' ' || *(s + 1) == '\0'))
nb++;
}
s = tmp;
return (nb);
}
/**
* strtow - split a string into words
* @str: string to split
*
* Return: pointer to the words
*/
char **strtow(char *str)
{
int nb, len, i = 0, j, check = 0;
char **s;
if (str == NULL || *str == '\0')
return (NULL);
nb = number_words(str);
if (nb == 0)
return (NULL);
s = malloc((nb + 1) * sizeof(char *));
if (s == NULL)
return (NULL);
for (; *str; str++)
{
if (*str != ' ' && check == 0)
{
len = word_len(str);
s[i] = malloc((len + 1) * sizeof(char));
if (s[i] == NULL)
return (NULL);
for (j = 0; j < len; j++, str++)
s[i][j] = *str;
i++;
check = 1;
}
if (*str == ' ')
check = 0;
}
return (s);
}