replace.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. /* If sub is empty, avoid an infinite loop */
  16. if (sub_len == 0)
  17. return strlen(str) + 1;
  18. while ((str = strstr(str, sub)) != NULL) {
  19. count++;
  20. str += sub_len;
  21. }
  22. return count;
  23. }
  24. char* FAST_FUNC xmalloc_substitute_string(const char *src, int count, const char *sub, const char *repl)
  25. {
  26. char *buf, *dst, *end;
  27. size_t sub_len = strlen(sub);
  28. size_t repl_len = strlen(repl);
  29. //dbg_msg("subst(s:'%s',count:%d,sub:'%s',repl:'%s'", src, count, sub, repl);
  30. buf = dst = xmalloc(strlen(src) + count * ((int)repl_len - (int)sub_len) + 1);
  31. /* we replace each sub with repl */
  32. while ((end = strstr(src, sub)) != NULL) {
  33. dst = mempcpy(dst, src, end - src);
  34. dst = mempcpy(dst, repl, repl_len);
  35. /*src = end + 1; - GNU findutils 4.5.10 doesn't do this... */
  36. src = end + sub_len; /* but this. Try "xargs -Iaa echo aaa" */
  37. }
  38. strcpy(dst, src);
  39. //dbg_msg("subst9:'%s'", buf);
  40. return buf;
  41. }