-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.c
More file actions
32 lines (28 loc) · 693 Bytes
/
replace.c
File metadata and controls
32 lines (28 loc) · 693 Bytes
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *replace(char *s, char *sub, char *rep)
{
int sublen;
int replen;
int ocurr;
int i;
char *pneedle;
static char newstr[1024]; /* OK for line size */
char tmp[200];
if (s == NULL || sub == NULL || rep == NULL) return NULL;
sublen = strlen(sub);
replen = strlen(rep);
i = 0;
for (ocurr = 0; (pneedle = strstr(s + i, sub)) != NULL; ++ocurr)
i = (int) (pneedle - s) + sublen;
strcpy(newstr, s);
i = 0;
while ((pneedle = strstr(newstr + i, sub)) != NULL) {
strcpy(tmp, pneedle + sublen);
sprintf(newstr + (pneedle - newstr), "%s%s", rep,
tmp);
i = (int) (pneedle - newstr) + replen;
}
return newstr;
}