replace.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. */
  9. //kbuild:lib-y += replace.o
  10. #include "libbb.h"
  11. unsigned FAST_FUNC count_strstr(const char *str, const char *sub)
  12. {
  13. size_t sub_len = strlen(sub);
  14. unsigned count = 0;
  15. while ((str = strstr(str, sub)) != NULL) {
  16. count++;
  17. str += sub_len;
  18. }
  19. return count;
  20. }
  21. char* FAST_FUNC xmalloc_substitute_string(const char *src, int count, const char *sub, const char *repl)
  22. {
  23. char *buf, *dst, *end;
  24. size_t sub_len = strlen(sub);
  25. size_t repl_len = strlen(repl);
  26. //dbg_msg("subst(s:'%s',count:%d,sub:'%s',repl:'%s'", src, count, sub, repl);
  27. buf = dst = xmalloc(strlen(src) + count * ((int)repl_len - (int)sub_len) + 1);
  28. /* we replace each sub with repl */
  29. while ((end = strstr(src, sub)) != NULL) {
  30. dst = mempcpy(dst, src, end - src);
  31. dst = mempcpy(dst, repl, repl_len);
  32. /*src = end + 1; - GNU findutils 4.5.10 doesn't do this... */
  33. src = end + sub_len; /* but this. Try "xargs -Iaa echo aaa" */
  34. }
  35. strcpy(dst, src);
  36. //dbg_msg("subst9:'%s'", buf);
  37. return buf;
  38. }