Skip to content

Commit 0c200dc

Browse files
committed
added: 2-str_concat.c
1 parent 3aa27ce commit 0c200dc

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

0x0B-malloc_free/2-main.c

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include "main.h"
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
5+
/**
6+
* main - check the code for ALX School students.
7+
*
8+
* Return: Always 0.
9+
*/
10+
int main(void)
11+
{
12+
char *s;
13+
14+
s = str_concat("Betty ", "Holberton");
15+
if (s == NULL)
16+
{
17+
printf("failed\n");
18+
return (1);
19+
}
20+
printf("%s\n", s);
21+
free(s);
22+
return (0);
23+
}

0x0B-malloc_free/2-str_concat.c

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include "main.h"
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
5+
/**
6+
* str_concat - concatenates two strings.
7+
*
8+
* @string1: first string.
9+
* @string2: second string.
10+
*
11+
* Return: pointer to the newly string.
12+
*/
13+
char *str_concat(char *string1, char *string2)
14+
{
15+
unsigned int index1, index2, counter;
16+
char *ptr;
17+
18+
for (index1 = 0; string1[index1];)
19+
index1++;
20+
21+
for (index2 = 0; string2[index2];)
22+
index2++;
23+
24+
ptr = malloc((index1 + index2 - 1) * sizeof(char));
25+
if (ptr == NULL)
26+
return (NULL);
27+
28+
counter = 0;
29+
for (index1 = 0; string1[index1]; index1++)
30+
{
31+
ptr[index1] = string1[index1];
32+
counter++;
33+
}
34+
35+
for (index2 = 0; string2[index2]; index2++)
36+
{
37+
ptr[counter] = string2[index2];
38+
counter++;
39+
}
40+
41+
ptr[counter] = string2[index2];
42+
return (ptr);
43+
}

0x0B-malloc_free/main.h

+1
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@
44
int _putchar(char c);
55
char *create_array(unsigned int, char);
66
char *_strdup(char *);
7+
char *str_concat(char *, char *);
78

89
#endif /* _MAIN_H_ */

0 commit comments

Comments
 (0)