-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strtrim.c
52 lines (46 loc) · 1.62 KB
/
ft_strtrim.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thakala <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/04 14:25:19 by thakala #+# #+# */
/* Updated: 2021/11/18 10:02:23 by thakala ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static int ft_is_whitespace(const char c)
{
return (c == ' ' || c == '\n' || c == '\t');
}
static size_t ft_strlen_trim(const char *s, int (*f)(char))
{
size_t len;
size_t whitespace_count;
len = 0;
whitespace_count = 0;
while (*s)
{
if (f(*s++))
whitespace_count++;
else
whitespace_count = 0;
len++;
}
return (len - whitespace_count);
}
char *ft_strtrim(char const *s)
{
size_t trimmed_len;
char *trimmed_str;
while (*s && ft_is_whitespace(*s))
s++;
trimmed_len = ft_strlen_trim(s, &ft_is_whitespace);
trimmed_str = (char *)malloc(sizeof(char) * (trimmed_len + 1));
if (!trimmed_str)
return (NULL);
ft_strncpy(trimmed_str, s, trimmed_len)[trimmed_len] = '\0';
return (trimmed_str);
}