minishell/libft/libft/ft_strtrim.c
2025-02-12 15:12:42 +01:00

84 lines
2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jguelen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/18 16:29:21 by jguelen #+# #+# */
/* Updated: 2024/10/23 13:15:24 by jguelen ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
#include <stdio.h>
static int ft_ischarinset(char c, const char *set)
{
while (*set)
{
if (c == *set)
return (1);
set++;
}
return (0);
}
/*til_trim is never used with NULL*/
static char *til_trim(const char *s1, const char *set)
{
char *valid_end;
valid_end = (char *)s1;
while (*s1)
{
if (!ft_ischarinset(*s1, set))
valid_end = (char *)s1;
s1++;
}
return (valid_end);
}
/* '\0' is presupposed not to be taken into account in set
Check if NULL protection of s1 needed or wanted*/
char *ft_strtrim(char const *s1, char const *set)
{
char *trim;
size_t trim_len;
size_t i;
i = 0;
if (s1 == NULL)
return (NULL);
while (*s1 && ft_ischarinset(*s1, set))
s1++;
trim = til_trim(s1, set);
trim_len = (size_t)(trim - s1) + 1;
if (*s1 == '\0')
trim_len = 0;
trim = (char *) malloc((trim_len + 1) * sizeof(char));
if (trim == NULL)
return (NULL);
while (i < trim_len)
{
trim[i] = s1[i];
i++;
}
trim[i] = '\0';
return (trim);
}
/*
int main(void)
{
char *s;
char *s1;
char *set;
s = "cabcdccc";
s1 = "";
set = "c";
printf("%s\n", ft_strtrim(s, set));
printf("%s\n", ft_strtrim(s1, set));
return (0);
}*/