ft_split
Subject
FT_SPLIT (simplified)
NAME
ft_split -- split a string into an array of words
SYNOPSIS
char **ft_split(const char *s, char c);
DESCRIPTION
Allocate (with malloc(3)) and returns an array of strings obtained by splitting s with the character c, used as delimiter.
The returned array must be NUL-terminated.
PARAMETERS
s: string to split
c: delimiter character
RETURN VALUES
ft_split() returns an array of strings resulting from the splitting of s; NULL if the memory allocation failed.
AUTHORIZED EXTERNAL FUNCTIONS
malloc(3)
Understandable explanation
You might have heard some things about ft_split()
but don't worry, I'll explain everything the best I can.
The subject tells us that ft_split()
must return an array of strings (=> an array of arrays, since strings are arrays of characters terminated by a NUL character).
We can also phrase that as an array of words, we take the string s
and we split it to get an array containing each words of it. Each word is separated by one or more c
, that's our word delimiter.
It's also said that our words array must be NUL-terminated. That means we have to allocate one more element in our array, that we can set to 0. By doing this we have an easy way to loop over our words array, the same as for a string: while(words[i] != 0)
.
The subject is not that hard to understand, the more complex thing is to your code do all that.
Hints
We don't have enough line in a single function to write ft_split()
so we'll have to write multiple functions.
I'll quickly get over all the things we have to do to achieve a functioning ft_split()
(the way I separate thing maybe is a sign ;))
Count how many words there is in the string, depending on the delimiter
Allocate an array of arrays (words array) big enough to hold all words + 1 that we can set to 0
Allocate a string for each words in our words array and copy the words in it
Free everything if we have a memory allocation error
char **ft_split(const char *s, char c)
{
/* allocate an array big enough to hold all the words in s */
/* loop over the string and find the start of the word */
/* find the end of the word */
/* copy the world at the first free index in our words array */
/* return our words array */
}
int word_count(/* whatever parameter you need */)
{
/* find and return the number of words in the string */
}
void ft_free(/* whatever argument you need */)
{
/* free EVERYTHING you allocated */
/* each element of the array as well as the array */
}
char *fill_word(/* whatever argument you need */)
{
/* allocate enough room for the word */
/* copy the word into the memory you allocated above */
/* return the allocated word */
}
Commented solution
Last updated
Was this helpful?