-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1-string_nconcat.c
63 lines (50 loc) · 1.04 KB
/
1-string_nconcat.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
#include "main.h"
/**
* _strlen - calculates the length of string
* @str: The string whose length is needed
*
* Return: The length of the str
*/
unsigned int _strlen(char *str)
{
unsigned int i;
i = 0;
while (str[i] != '\0')
i++;
return (i);
}
/**
* string_nconcat - concatenates two string give a size for string 2
* @s1: first string
* @s2: second string
* @n: Third string
*
* Return: Concatenated string
*/
char *string_nconcat(char *s1, char *s2, unsigned int n)
{
char *str;
unsigned int i, len2;
if (s1 == NULL)
s1 = "";
if (s2 == NULL)
s2 = "";
if (n >= _strlen(s2))
str = (char *)malloc(sizeof(_strlen(s1)) + _strlen(s2) + 2);
if (n < _strlen(s2))
str = (char *)malloc(sizeof(_strlen(s1)) + n + 2);
if (str == NULL)
return (NULL);
len2 = _strlen(s1);
if (1)
for (i = 0; i < len2; i++)
str[i] = s1[i];
if (n >= _strlen(s2))
for (i = 0; i < _strlen(s2); i++)
str[_strlen(s1) + i] = s2[i];
else
for (i = 0; i < n; i++)
str[_strlen(s1) + i] = s2[i];
str[_strlen(s1) + i] = '\0';
return (str);
}