-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strjoin.c
68 lines (59 loc) · 1.17 KB
/
ft_strjoin.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
/*
* ft_strjoin(): concatenate two strings into a new string (with malloc).
*
* DESCRIPTION:
* ============
* Allocates (with malloc(3)) and returns a new string, which is the
* result of the concatenation of ’s1’ and ’s2’.
* return a pointer to the new string.
*/
# include <stdlib.h>
# include <stdio.h>
# include <string.h>
char *ft_strjoin(char const *s1, char const *s2)
{
size_t i;
size_t j;
size_t new_str_len;
char *new_str;
i = 0;
j = 0;
new_str_len = strlen(s1) + strlen(s2);
// we added (1) for '\0'.
new_str = (char *)malloc(new_str_len + 1);
if (!s1 || !s2 || !new_str)
{
return (0);
}
// Adding the first string to new_str.
while (s1[i] != '\0')
{
new_str[i] = s1[i];
i++;
}
//Adding the second string to new_str.
while (s2[j] != '\0')
{
new_str[i] = s2[j];
i++;
j++;
}
// ending the new string with '\0'.
new_str[i] = '\0';
return (new_str);
}
int main()
{
char const *s1;
char const *s2;
s1 = "12345";
s2 = "67890";
printf("The result from st_strjoin() is : %s\n", ft_strjoin(s1, s2));
return EXIT_SUCCESS;
}
/*
* Note:
* =====
* Don't forget to replace strlen() with ft_strlen() and include the header
* libft.h
*/