-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_functions_1.c
141 lines (105 loc) · 2.39 KB
/
string_functions_1.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include "shell.h"
/**
* stringcopy - Copies a string from one string array to another
* @target: A pointer to the target string array to copy to
* @source: A pointer to the source string
* Return: A pointer to the target string
*/
char *stringcopy(char *target, char *source)
{
int idx = 0; /* index to loop through source string */
if (target == source || source == 0)
return (target);
/* Copy source string into target string */
while (source[idx] != '\0')
{
target[idx] = source[idx];
idx += 1;
}
target[idx] = '\0';
return (target);
}
/**
* stringcompare - Compares two strings
* @string1: A pointer to the 1st string
* @string2: A pointer to the 2nd string
* Return: 0 if string1 = string2
* positive or negative integer if otherwise
*/
int stringcompare(char *string1, char *string2)
{
int idx = 0;
if (string1 == NULL || string2 == NULL)
{
if (string1 == NULL && string2 == NULL)
return (0);
else
return (-1);
}
while (string1[idx] != '\0' && string2[idx] != '\0')
{
if (string1[idx] != string2[idx])
return (string1[idx] - string2[idx]);
idx += 1;
}
if (string1[idx] != '\0' || string2[idx] != '\0')
return (string1[idx] - string2[idx]);
return (0);
}
/**
* stringlength - Calculates the length of a string
* @str: A pointer to the string input
* Return: Length of the string input
*/
int stringlength(char *str)
{
int len = 0;
while (str[len] != '\0')
len++;
return (len);
}
/**
* stringconcat - Concatenates two strings
* @target: A pointer to the target string array to copy to
* @source: A pointer to the source string
* Return: A pointer to the target string
*/
char *stringconcat(char *target, char *source)
{
int targetlen = 0, idx = 0;
while (target[idx] != '\0')
{
targetlen += 1;
idx++;
}
idx = 0;
while (source[idx] != '\0')
{
target[targetlen + idx] = source[idx];
idx++;
}
target[targetlen + idx] = '\0';
return (target);
}
/**
* stringdup - Duplicates a string from one string array to a buffer
* @source: A pointer to the source string to duplicate
* Return: A pointer to the target string
*/
char *stringdup(const char *source)
{
int len = 0, idx;
char *target;
if (source == NULL)
return (NULL);
while (source[len] != '\0')
len++;
target = malloc(sizeof(char) * (len + 1));
if (target == NULL)
return (NULL);
for (idx = 0 ; idx <= len ; idx++)
{
target[idx] = source[idx];
}
return (target);
}