-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.c
More file actions
59 lines (50 loc) · 1.7 KB
/
replace.c
File metadata and controls
59 lines (50 loc) · 1.7 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
#include "my_str.h"
char *replace(char *s, char *pat, char *rep) {
int size = 1;
char *cache = malloc(size * sizeof(char));
char *cacheWriter = cache;
char *sIterator = s;
char *sPatChecker;
char *patIterator = pat;
char *repIterator = rep;
while (*sIterator != '\0') {
if (*sIterator == *pat) {
//check to see if the part is equal
int toggle = 1;
sPatChecker = sIterator;
while (*patIterator != '\0') {
if (*sPatChecker == *patIterator) {
sPatChecker++;
patIterator++;
} else {
toggle = 0;
break;
}
}
patIterator = pat; //reset to beginning position
if (toggle == 0) { //not equal to pat
*cacheWriter = *sIterator;
cache = realloc(cache, ++size * sizeof(char));
cacheWriter++;
sIterator++;
} else { //replace pat with rep
sIterator = sPatChecker; //pushes iterator to after pat is done
while (*repIterator != '\0') {
//copies rep into cache
*cacheWriter = *repIterator;
repIterator++;
cacheWriter++;
cache = realloc(cache, ++size * sizeof(char));
}
repIterator = rep; //reset to beginning position
}
} else {
*cacheWriter = *sIterator;
cache = realloc(cache, ++size * sizeof(char));
cacheWriter++;
sIterator++;
}
}
*cacheWriter = '\0';
return cache;
}