-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenization.c
107 lines (87 loc) · 1.96 KB
/
tokenization.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
#include "text.h"
/**
* split_words - Split a line into words
*
* @line: Line to spli
* @sep: Delimiters for split the words
*
* Return: Set of words
**/
char **split_words(char *line, const char *sep)
{
char **words, **tmp, *token;
size_t new_size, old_size;
old_size = sizeof(char *);
words = malloc(old_size);
if (words != NULL)
{
new_size = 1;
token = strtok(line, sep);
while (token)
{
if (token[0] == '#')
break;
tmp = _realloc(words, old_size, (new_size + 1) * sizeof(char *));
old_size = (new_size + 1) * sizeof(char *);
if (tmp == NULL)
break;
words = tmp;
++new_size;
words[new_size - 2] = malloc(_strlen(token) + 1);
if (words == NULL)
{
free(tmp);
free(words);
}
if (words[new_size - 2] != NULL)
_strcpy(words[new_size - 2], token);
token = strtok(NULL, sep);
tmp = NULL;
}
words[new_size - 1] = NULL;
}
return (words);
}
/**
* join_words - Join 3 words with a separator
* Description: Result -> w1.sep.w2.sep.nl
* @word1: Word1 to join
* @word2: Word2 to join
* @word3: Word3 to join
* @sep: Separator between the words
*
* Return: Line composed by 3 parts followed by a separator and
* end by a new line
**/
char *join_words(char *word1, char *word2, char *word3, const char *sep)
{
char *aux;
int size_str1, size_str2, size_str3, size_sep;
size_str1 = size_str2 = size_sep = 0;
if (word1 != NULL)
size_str1 = _strlen(word1);
else
word1 = "";
if (word2 != NULL)
size_str2 = _strlen(word2);
else
word2 = "";
if (word3 != NULL)
size_str3 = _strlen(word3);
else
word3 = "";
if (sep != NULL)
size_sep = _strlen((char *) sep);
else
sep = "";
aux = malloc(size_str1 + size_str2 + size_sep + size_str3 + size_sep + 2);
if (aux == NULL)
return (NULL);
aux = _strcpy(aux, word1);
aux = _strcat(aux, (char *) sep);
aux = _strcat(aux, word2);
aux = _strcat(aux, (char *) sep);
aux = _strcat(aux, word3);
aux = _strcat(aux, "\n");
return (aux);
}