commit a7662dfad06c9cc6d930d627829d301d85fefa43
parent dbc5007c9dd9bfabad376d74e55b9f2c65584a64
Author: sin <sin@2f30.org>
Date: Tue, 6 May 2014 13:38:22 +0100
Add replace_str()
Diffstat:
4 files changed, 41 insertions(+), 2 deletions(-)
diff --git a/Makefile b/Makefile
@@ -3,7 +3,7 @@
include config.mk
-SRC = fifo.c stack.c tokenize.c vector.c
+SRC = fifo.c stack.c str.c tokenize.c vector.c
OBJ = ${SRC:.c=.o}
SOUT = ${NAME}.a
diff --git a/ds.h b/ds.h
@@ -16,6 +16,9 @@ void *stack_push(struct stack *, void *);
void *stack_pop(struct stack *);
void *stack_peek(struct stack *);
+/* str.c */
+char *replace_str(const char *, const char *, const char *);
+
/* tokenize.c */
int gettokens(char *, char **, int, char *);
int tokenize(char *, char **, int);
diff --git a/stack.c b/stack.c
@@ -1,4 +1,3 @@
-#include <stdio.h>
#include <stdlib.h>
struct stacknode {
diff --git a/str.c b/str.c
@@ -0,0 +1,37 @@
+/* Taken from: http://creativeandcritical.net/str-replace-c/ */
+/* Released in the public domain */
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+
+char *
+replace_str(const char *str, const char *old, const char *new)
+{
+ char *ret, *r;
+ const char *p, *q;
+ size_t oldlen = strlen(old);
+ size_t count, retlen, newlen = strlen(new);
+
+ if (oldlen != newlen) {
+ for (count = 0, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen)
+ count++;
+ /* this is undefined if p - str > PTRDIFF_MAX */
+ retlen = p - str + strlen(p) + count * (newlen - oldlen);
+ } else
+ retlen = strlen(str);
+
+ if ((ret = malloc(retlen + 1)) == NULL)
+ return NULL;
+
+ for (r = ret, p = str; (q = strstr(p, old)) != NULL; p = q + oldlen) {
+ /* this is undefined if q - p > PTRDIFF_MAX */
+ ptrdiff_t l = q - p;
+ memcpy(r, p, l);
+ r += l;
+ memcpy(r, new, newlen);
+ r += newlen;
+ }
+ strcpy(r, p);
+
+ return ret;
+}