46 lines
1.7 KiB
C
Executable file
46 lines
1.7 KiB
C
Executable file
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_substr.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: thrieg <thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/10/15 11:27:50 by thrieg #+# #+# */
|
|
/* Updated: 2025/02/16 19:05:22 by thrieg ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
|
|
static void ft_memcpy_with_nullchar(char *substring, char const *s, size_t len)
|
|
{
|
|
ft_memcpy(substring, s, len);
|
|
substring[len] = '\0';
|
|
}
|
|
|
|
//check for out of bound access and return NULL if s is NULL or allocation fails
|
|
//len 0 or out of bound start just returns a null character
|
|
char *ft_substr(char const *s, unsigned int start, size_t len)
|
|
{
|
|
char *substring;
|
|
size_t slen;
|
|
|
|
if (!s)
|
|
return (NULL);
|
|
slen = ft_strlen(s);
|
|
if (slen <= start)
|
|
return (ft_strdup(""));
|
|
s = &s[start];
|
|
slen -= start;
|
|
if (slen > len)
|
|
substring = malloc(sizeof(char) * (len + 1));
|
|
else
|
|
substring = malloc(sizeof(char) * (slen + 1));
|
|
if (!substring)
|
|
return (NULL);
|
|
if (slen > len)
|
|
ft_memcpy_with_nullchar(substring, s, len);
|
|
else
|
|
ft_memcpy_with_nullchar(substring, s, slen);
|
|
return (substring);
|
|
}
|