-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strtrim.c
83 lines (76 loc) · 1.97 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cyildiri <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/03 21:43:21 by cyildiri #+# #+# */
/* Updated: 2016/10/04 16:56:08 by cyildiri ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_find_start(char const *s, int *index, int low)
{
while (s[*index] != '\0')
{
if (!ft_isspace(s[*index]) && low == -1)
low = *index;
(*index)++;
}
(*index)--;
return (low);
}
static int ft_find_end(char const *s, int *index, int high)
{
while (*index >= 0 && high != *index)
{
if (!ft_isspace(s[*index]) && high == -1)
{
high = *index;
break ;
}
(*index)--;
}
return (high);
}
static char *ft_copy_str(char const *s, char *out_str, int high, int low)
{
int len;
int index;
int i;
len = (high + 1) - low;
index = high;
i = len - 1;
while (index >= low)
{
out_str[i] = s[index];
i--;
index--;
}
return (out_str);
}
char *ft_strtrim(char const *s)
{
int index;
char *out_str;
int high;
int low;
if (s == NULL)
return (NULL);
index = 0;
low = ft_find_start(s, &index, -1);
high = ft_find_end(s, &index, -1);
if (low == high)
{
if (!(out_str = ft_strnew(0)))
return (NULL);
}
else
{
if (!(out_str = ft_strnew((high + 1) - low)))
return (NULL);
out_str = ft_copy_str(s, out_str, high, low);
}
return (out_str);
}