-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplacestr.c
56 lines (53 loc) · 1.12 KB
/
replacestr.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
56
/*
* $Log: replacestr.c,v $
* Revision 1.1 2020-07-19 18:26:54+05:30 Cprogrammer
* Initial revision
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_QMAIL
#include <stralloc.h>
#include <strerr.h>
#include <str.h>
#endif
#ifndef lint
static char sccsid[] = "$Id: replacestr.c,v 1.1 2020-07-19 18:26:54+05:30 Cprogrammer Exp mbhangui $";
#endif
/*
* returns 0 if search string ch not found
* and leaves buf untouched
*/
int
replacestr(char *str, char *ch, char *rch, stralloc *buf)
{
int chlen, rchlen, prev;
register int i, cnt;
register char *ptr, *s;
chlen = str_len(ch);
rchlen = str_len(rch);
for (ptr = str, prev = cnt = 0; *ptr;) {
if (!(s = str_str(ptr, ch)))
break;
if (!cnt)
buf->len = 0;
i = s - str;
if (!stralloc_catb(buf, ptr, i - prev))
return (-1);
if (!stralloc_catb(buf, rch, rchlen))
return (-1);
ptr = str + i + chlen; /*- move past the found character */
prev = i + chlen;
cnt++;
}
if (cnt) {
/*- copy remaining data */
if (!stralloc_cats(buf, ptr))
return (-1);
if (!stralloc_0(buf))
return (-1);
buf->len--;
}
return (cnt);
}