summaryrefslogtreecommitdiff
path: root/src/string-util.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/string-util.c')
-rw-r--r--src/string-util.c38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/string-util.c b/src/string-util.c
index e183288..d5a702b 100644
--- a/src/string-util.c
+++ b/src/string-util.c
@@ -19,6 +19,7 @@
#include <sys/types.h>
#include <string.h>
+#include <stdlib.h>
/*
* Copy src to string dst of size siz. At most siz-1 characters
@@ -83,3 +84,40 @@ size_t strlcat(char *dst, const char *src, size_t siz)
return (dlen + (s - src)); /* count does not include NUL */
}
+
+char *str_replace(const char *str, const char *old, const char *new)
+{
+ const char *ins;
+ char *result, *tmp;
+ size_t len_old, len_new, len_front, len_result;
+ int count;
+
+ if (!str || !old || !new)
+ return NULL;
+ len_old = strlen(old);
+ if (len_old == 0)
+ return NULL;
+ len_new = strlen(new);
+
+ ins = str;
+ for (count = 0; (tmp = strstr(ins, old)); ++count) {
+ ins = tmp + len_old;
+ }
+
+ len_result = strlen(str) + (len_new - len_old) * count + 1;
+ tmp = result = malloc(len_result);
+ if (!result)
+ return NULL;
+
+ while (count--) {
+ ins = strstr(str, old);
+ len_front = ins - str;
+ tmp = strncpy(tmp, str, len_front) + len_front;
+ strlcpy(tmp, new, len_result);
+ tmp += len_new;
+ str += len_front + len_old;
+ }
+ strlcpy(tmp, str, len_result);
+ return result;
+}
+