-
Notifications
You must be signed in to change notification settings - Fork 0
Implementation
Alisson edited this page Aug 12, 2023
·
1 revision
ft_substr - return a new substring of string *s that begin at s[start] and have at most len of length.
If start doesn't exists in *s, we return an error. The error is a memory block of a single byte that is set to NULL, returned by ft_calloc.
See that new_str_len = ft_strlen(s + start), so if len < new_str_len we have to alocate only len bytes. Otherwise, mean that len > new_str_len and we have to allocate new_str_len. Alocate new_str_len to copy the string s[start] mean duplicate the string s[start], so I call ft_strdup(s + start).
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *new_str;
size_t new_str_len;
size_t s_len;
if (!s)
return (NULL);
s_len = ft_strlen(s);
if (start > s_len)
return ((char *)ft_calloc(1, sizeof(char)));
new_str_len = ft_strlen(s + start);
if (len < new_str_len)
{
new_str = ft_calloc(len + 1, sizeof(char));
if (!new_str)
return (NULL);
ft_strlcpy(new_str, s + start, len + 1);
return (new_str);
}
return (ft_strdup(s + start));
}