busybox: update to 1.23.2
[tomato.git] / release / src / router / busybox / libbb / replace.c
blob8711f957daae242ea362b3726ea32c6367825083
1 /* vi: set sw=4 ts=4: */
2 /*
3 * Utility routines.
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8 */
10 //kbuild:lib-y += replace.o
12 #include "libbb.h"
14 unsigned FAST_FUNC count_strstr(const char *str, const char *sub)
16 size_t sub_len = strlen(sub);
17 unsigned count = 0;
19 while ((str = strstr(str, sub)) != NULL) {
20 count++;
21 str += sub_len;
23 return count;
26 char* FAST_FUNC xmalloc_substitute_string(const char *src, int count, const char *sub, const char *repl)
28 char *buf, *dst, *end;
29 size_t sub_len = strlen(sub);
30 size_t repl_len = strlen(repl);
32 //dbg_msg("subst(s:'%s',count:%d,sub:'%s',repl:'%s'", src, count, sub, repl);
34 buf = dst = xmalloc(strlen(src) + count * ((int)repl_len - (int)sub_len) + 1);
35 /* we replace each sub with repl */
36 while ((end = strstr(src, sub)) != NULL) {
37 dst = mempcpy(dst, src, end - src);
38 dst = mempcpy(dst, repl, repl_len);
39 /*src = end + 1; - GNU findutils 4.5.10 doesn't do this... */
40 src = end + sub_len; /* but this. Try "xargs -Iaa echo aaa" */
42 strcpy(dst, src);
43 //dbg_msg("subst9:'%s'", buf);
44 return buf;