-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmy_string.c
More file actions
67 lines (62 loc) · 1.57 KB
/
my_string.c
File metadata and controls
67 lines (62 loc) · 1.57 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
61
62
63
64
65
66
67
/*******************************************************************************
*
* File Name : my_string.c
* Created By : Thomas Aurel
* Creation Date : January 15th, 2015
* Last Change : April 22th, 2015 at 22:09:15
* Last Changed By : Thomas Aurel
* Purpose : string specific functions
*
*******************************************************************************/
#include <stdlib.h>
#include "my_stdio.h"
#include "my_string.h"
int my_strlen(char *str){
int i = 0;
while (str[i] != '\0'){
i++;
}
return i;
}
char * my_strcat(char *s1, char *s2){
return my_strncat(s1, s2, my_strlen(s2));
}
char * my_strncat(char *s1, char *s2, int n){
int size = my_strlen(s1);
char *tmp;
if ((tmp = (char *)malloc((size+n)*sizeof(char)))==NULL){
my_puts("ERROR: malloc failed\n");
return NULL;
}
for (int i=0; i < size + n; i++){
if (i < size){
tmp[i] = s1[i];
} else {
tmp[i] = s2[i - size];
}
}
tmp[size + n] = '\0';
s1 = tmp;
free(tmp);
return s1;
}
char * my_strcpy(char *dest, char *src){
return my_strncpy(dest, src, my_strlen(src));
}
char * my_strncpy(char *dest, char *src, int n){
char *tmp;
if ((tmp = (char *)malloc(n*sizeof(char)))==NULL){
my_puts("ERROR: malloc failed\n");
return NULL;
}
for (int i=0; i < n; i++){
if(i < my_strlen(src)){
tmp[i] = src[i];
}else{
tmp[i] = '\0';
}
}
dest = tmp;
free(tmp);
return dest;
}