libft/ft_substr.c

64 lines
1.8 KiB
C
Raw Normal View History

2024-10-17 12:00:30 +02:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/17 11:45:52 by kcolin #+# #+# */
/* Updated: 2024/10/23 10:46:53 by kcolin ### ########.fr */
2024-10-17 12:00:30 +02:00
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static int min(size_t a, size_t b)
{
if (a > b)
return (b);
return (a);
}
2024-10-17 12:00:30 +02:00
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *out;
size_t substr_len;
size_t i;
2024-10-17 12:00:30 +02:00
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, len) + 1, sizeof(char));
2024-10-17 12:00:30 +02:00
if (out == NULL)
return (NULL);
ft_strlcpy(out, s + start, min(substr_len, len) + 1);
2024-10-17 12:00:30 +02:00
return (out);
}
/*
#include <stdio.h> // BAD
#include <stdint.h> // BAD
2024-10-17 12:00:30 +02:00
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, 0, SIZE_MAX));
2024-10-17 12:00:30 +02:00
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));
2024-10-17 12:00:30 +02:00
}
*/