-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.c
More file actions
62 lines (55 loc) · 1.64 KB
/
Copy pathreplace.c
File metadata and controls
62 lines (55 loc) · 1.64 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
#include "replace.h"
int replace(char** text, char* pattern, char* target) {
char* new_text;
size_t capacity = REPLACE_PAGE_SIZE;
size_t target_size = strlen(target);
size_t last = 0;
size_t i = 0;
if (pattern == NULL || target == NULL || text == NULL || *text == NULL)
return REPLACE_INVALID_POINTER;
if (*pattern == '\0')
return REPLACE_EMPTY_PATTERN;
new_text = (char*)malloc(capacity * sizeof(char));
if (new_text == NULL)
return REPLACE_NOT_ENOUGH_MEMORY;
while ((*text)[i] != '\0')
{
size_t j = 0;
size_t count = target_size;
while (pattern[j] != '\0' && (*text)[i + j] != '\0' && (*text)[i + j] == pattern[j])
{
++j;
}
if (pattern[j] != '\0')
count = j;
if (last + count >= capacity)
{
char *ptr;
while (last + count >= capacity)
capacity += REPLACE_PAGE_SIZE;
ptr = (char*)realloc(new_text, capacity);
if (ptr = NULL)
return REPLACE_NOT_ENOUGH_MEMORY;
new_text = ptr;
}
if (j == 0)
new_text[last++] = (*text)[i++];
else if (pattern[j] == '\0')
{
size_t index = 0;
while (target[index] != '\0')
new_text[last++] = target[index++];
i += j;
}
else
{
size_t index;
for (index = 0; index < j; ++index)
new_text[last++] = (*text)[i++];
}
}
free(*text);
new_text[last] = '\0';
*text = new_text;
return REPLACE_SUCCESS_RETVAL;
}