-
Notifications
You must be signed in to change notification settings - Fork 1
/
str_replace.c
57 lines (48 loc) · 1.64 KB
/
str_replace.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
#include "str_replace.h"
#include <string.h>
#include <stdlib.h>
// You must free the result if result is non-NULL.
char *str_replace(const char *orig, const char *rep, const char *with, unsigned int max_replacements) {
char *result; // the return string
const char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep
int len_with; // length of with
int len_front; // distance between rep and end of last rep
int count; // number of replacements
if (!orig)
return NULL;
if (!rep)
rep = "";
len_rep = strlen(rep);
if (!len_rep) {
return NULL; //undefined, how can we replace nothing with something
}
if (!with)
with = "";
len_with = strlen(with);
ins = orig;
for (count = 0; (tmp = strstr(ins, rep)); ++count) {
ins = tmp + len_rep;
}
if (max_replacements != 0 && count > max_replacements) {
count = max_replacements;
}
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}