This repository was archived by the owner on Jun 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.c
More file actions
60 lines (52 loc) · 1.44 KB
/
string.c
File metadata and controls
60 lines (52 loc) · 1.44 KB
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
#include "string.h"
char *strcpy(char *s1, const char *s2)
{
strncpy(s1, s2, strlen(s2) + 1);
s1[strlen(s2)] = '\0'; //tack on the null terminating character if it wasn't already done
return s1;
}
char *strncpy(char *s1, const char *s2, size_t n)
{
unsigned int extern_iter = 0; //when s2's length is shorter than n, this allows the function to continue padding null characters
unsigned int iterator = 0;
for (iterator = 0; iterator < n; iterator++) //iterate through s2 up to char n, copying them to s1
{
if (s2[iterator] != '\0')
s1[iterator] = s2[iterator];
else //the end of s2 was found prematurely - copy the null character, update external iterator and quit for loop
{
s1[iterator] = s2[iterator];
extern_iter = iterator + 1;
break;
}
}
while (extern_iter < n) //while there are still spaces that need to be filled with null characters, fill them
{
s1[extern_iter] = '\0';
extern_iter++;
}
return s1;
}
int strcmp(const char *s1, const char *s2)
{
if (strlen(s1) != strlen(s2))
return s2-s1;
return strncmp(s1, s2, strlen(s1)); //It doesn't matter what the n is at this point - they should be the same length anyways
}
int strncmp(const char *s1, const char *s2, size_t n)
{
unsigned int count = 0;
while (count < n)
{
if (s1[count] == s2[count])
{
if (s1[count] == '\0') //quit early because null-termination found
return 0;
else
count++;
}
else
return s1[count] - s2[count];
}
return 0;
}