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