From 409bc9c33e99d5bb1e04d01bf3c75854d3a5dc7e Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 14 Nov 2012 22:16:23 +0100 Subject: [PATCH] util: add strreplace() to replace a substring by another string --- src/shared/util.c | 50 +++++++++++++++++++++++++++++++++++++++++++++++ src/shared/util.h | 2 ++ 2 files changed, 52 insertions(+) diff --git a/src/shared/util.c b/src/shared/util.c index 5a326ec43..6d826b6f5 100644 --- a/src/shared/util.c +++ b/src/shared/util.c @@ -6163,3 +6163,53 @@ const char *draw_special_char(DrawSpecialChar ch) { return draw_table[!is_locale_utf8()][ch]; } + +char *strreplace(const char *text, const char *old_string, const char *new_string) { + const char *f; + char *t, *r; + size_t l, old_len, new_len; + + assert(text); + assert(old_string); + assert(new_string); + + old_len = strlen(old_string); + new_len = strlen(new_string); + + l = strlen(text); + r = new(char, l+1); + if (!r) + return NULL; + + f = text; + t = r; + while (*f) { + char *a; + size_t d, nl; + + if (!startswith(f, old_string)) { + *(t++) = *(f++); + continue; + } + + d = t - r; + nl = l - old_len + new_len; + a = realloc(r, nl + 1); + if (!a) + goto oom; + + l = nl; + r = a; + t = r + d; + + t = stpcpy(t, new_string); + f += old_len; + } + + *t = 0; + return r; + +oom: + free(r); + return NULL; +} diff --git a/src/shared/util.h b/src/shared/util.h index c2bed2a84..a148ebbc5 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -611,3 +611,5 @@ typedef enum DrawSpecialChar { _DRAW_SPECIAL_CHAR_MAX } DrawSpecialChar; const char *draw_special_char(DrawSpecialChar ch); + +char *strreplace(const char *text, const char *old_string, const char *new_string); -- 2.30.2