61 lines
1.7 KiB
C
61 lines
1.7 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_substr.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/10/17 11:45:52 by kcolin #+# #+# */
|
|
/* Updated: 2024/10/19 18:34:36 by kcolin ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
#include <stdlib.h>
|
|
|
|
static int min(size_t a, size_t b)
|
|
{
|
|
if (a > b)
|
|
return (b);
|
|
return (a);
|
|
}
|
|
|
|
char *ft_substr(char const *s, unsigned int start, size_t len)
|
|
{
|
|
char *out;
|
|
size_t substr_len;
|
|
size_t i;
|
|
|
|
substr_len = 0;
|
|
i = 0;
|
|
while (s[i] != '\0')
|
|
{
|
|
if (i >= start)
|
|
substr_len++;
|
|
if (i >= start + len)
|
|
break ;
|
|
i++;
|
|
}
|
|
if (i < start)
|
|
return (ft_calloc(1, sizeof(char)));
|
|
out = ft_calloc(min(substr_len + 1, len + 1), sizeof(char));
|
|
if (out == NULL)
|
|
return (NULL);
|
|
ft_strlcpy(out, s + start, len + 1);
|
|
return (out);
|
|
}
|
|
|
|
/*
|
|
#include <stdio.h> // BAD
|
|
|
|
int main(void)
|
|
{
|
|
char *data = "This is a long test string.";
|
|
|
|
printf("'%s'\n", ft_substr(data, 0, 4));
|
|
printf("'%s'\n", ft_substr(data, 15, 4));
|
|
printf("'%s'\n", ft_substr(data, 15, 0));
|
|
printf("'%s'\n", ft_substr(data, 20, 20));
|
|
printf("'%s'\n", ft_substr(data, 100, 27));
|
|
}
|
|
*/
|