1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9 //kbuild:lib-y += replace.o
13 unsigned FAST_FUNC count_strstr(const char *str, const char *sub)
15 size_t sub_len = strlen(sub);
18 /* If sub is empty, avoid an infinite loop */
20 return strlen(str) + 1;
22 while ((str = strstr(str, sub)) != NULL) {
29 char* FAST_FUNC xmalloc_substitute_string(const char *src, int count, const char *sub, const char *repl)
31 char *buf, *dst, *end;
32 size_t sub_len = strlen(sub);
33 size_t repl_len = strlen(repl);
35 //dbg_msg("subst(s:'%s',count:%d,sub:'%s',repl:'%s'", src, count, sub, repl);
37 buf = dst = xmalloc(strlen(src) + count * ((int)repl_len - (int)sub_len) + 1);
38 /* we replace each sub with repl */
39 while ((end = strstr(src, sub)) != NULL) {
40 dst = mempcpy(dst, src, end - src);
41 dst = mempcpy(dst, repl, repl_len);
42 /*src = end + 1; - GNU findutils 4.5.10 doesn't do this... */
43 src = end + sub_len; /* but this. Try "xargs -Iaa echo aaa" */
46 //dbg_msg("subst9:'%s'", buf);