ft_strtrim.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* ft_strtrim.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: abonnard <abonnard@student.42nice.fr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2024/11/05 13:31:24 by abonnard #+# #+# */ 9 /* Updated: 2024/11/05 17:38:50 by abonnard ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include <stdlib.h> 14 #include "../include/libft.h" 15 16 static int ft_is_in_set(char c, const char *set) 17 { 18 int j; 19 20 j = 0; 21 while (set[j]) 22 { 23 if (c == set[j]) 24 return (1); 25 j++; 26 } 27 return (0); 28 } 29 30 static int ft_trim_start(const char *s1, const char *set) 31 { 32 int i; 33 34 i = 0; 35 while (s1[i] && ft_is_in_set(s1[i], set)) 36 i++; 37 return (i); 38 } 39 40 static int ft_trim_end(const char *s1, const char *set) 41 { 42 int len; 43 44 len = 0; 45 while (s1[len]) 46 len++; 47 len--; 48 while (len >= 0 && ft_is_in_set(s1[len], set)) 49 len--; 50 return (len + 1); 51 } 52 53 char *ft_strtrim(char const *s1, char const *set) 54 { 55 char *str; 56 int start; 57 int end; 58 int i; 59 60 if (!s1 || !set) 61 return (NULL); 62 start = ft_trim_start(s1, set); 63 end = ft_trim_end(s1, set); 64 if (start >= end) 65 str = malloc(sizeof(char)); 66 if (!str) 67 return (NULL); 68 str[0] = '\0'; 69 return (str); 70 str = malloc(sizeof(char) * (end - start + 1)); 71 if (!str) 72 return (NULL); 73 i = 0; 74 while (start < end) 75 str[i++] = s1[start++]; 76 str[i] = '\0'; 77 return (str); 78 }