-
Notifications
You must be signed in to change notification settings - Fork 0
/
strtow.c
141 lines (136 loc) · 2.51 KB
/
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include "main.h"
/**
* word_count - count the number of words in a string
* @str: string
* @delim: delimeter
* Return: number of words in a string
*/
int word_count(char *str, char delim)
{
int i = 1;
int words = 0;
if (str[0] != delim)
words++;
for (; str[i] != '\0'; i++)
{
if (str[i] != delim && str[i - 1] == delim)
words++;
}
return (words);
}
/**
* word_length - calculates the length of each word in a string
* @str: string
* @word: The word in the string whose length is to be calculated.
* @delim: delimeter
* e.g: first word, second word, third word and so on
* Return: length of word in a string
*/
int word_length(char *str, int word, char delim)
{
int i = 1, j = 0, words = 0;
if (str[0] != delim)
{
words++;
if (word == words)
{
while (str[j] != delim && str[j] != '\0')
j++;
return (j);
}
}
for (; str[i] != '\0'; i++)
{
if (str[i] != delim && str[i - 1] == delim)
{
words++;
if (word == words)
{
while (str[i] != delim && str[i] != '\0')
{
i++;
j++;
}
break;
}
}
}
return (j);
}
/**
* get_word - gets the word in a string
* @str: string
* @word: word to be gotten. e.g whether first word, second word or third word
* and so on is to be gotten
* @delim: delimeter
* Return: gotten word
*/
char *get_word(char *str, int word, char delim)
{
int i = 1;
int words = 0;
if (str[0] != delim)
{
words++;
if (word == words)
{
return (&str[0]);
}
}
for (; str[i] != '\0'; i++)
{
if (str[i] != delim && str[i - 1] == delim)
{
words++;
if (word == words)
{
return (&str[i]);
}
}
}
return (0);
}
/**
* strtow - converts a string to array of words
* @str: string
* @delim: delimeter
* Return: array of words
*/
char **strtow(char *str, char delim)
{
int total_word = word_count(str, delim);
int i, j, k, string_length;
char **string_arr;
char *tmp;
if (str == NULL || total_word == 0)
{
return (NULL);
}
string_arr = malloc((total_word + 1) * sizeof(char *));
if (string_arr == NULL)
return (NULL);
for (i = 0; i < total_word; i++)
{
string_arr[i] = malloc(word_length(str, i + 1, delim) + 1);
if (string_arr[i] == NULL)
{
free(string_arr);
return (NULL);
}
}
for (k = 0; k < total_word; k++)
{
string_length = word_length(str, k + 1, delim);
for (j = 0; j < string_length; j++)
{
tmp = get_word(str, k + 1, delim);
if (*(tmp + j) != delim)
{
string_arr[k][j] = *(tmp + j);
}
}
string_arr[k][j] = '\0';
}
string_arr[i] = NULL;
return (string_arr);
}