From dd9c9752ead3a39fec6f050bfe3ac8768defc02f Mon Sep 17 00:00:00 2001 From: Keith Kanios Date: Fri, 8 Apr 2011 00:23:21 -0500 Subject: [PATCH] nasmlib: added string replace (strrep) utility function --- nasmlib.c | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ nasmlib.h | 5 ++++ 2 files changed, 85 insertions(+) diff --git a/nasmlib.c b/nasmlib.c index d70f6c24..538223f8 100644 --- a/nasmlib.c +++ b/nasmlib.c @@ -290,6 +290,86 @@ char *nasm_strsep(char **stringp, const char *delim) } #endif +char *nasm_strrep(const char *str, const char *sub, char *lin, bool casesense) +{ + char *outline = lin; + char *temp1 = NULL; + char *temp2 = NULL; + char *l, *lp, *lt, *ls; + int count = 0; + int str_len, sub_len, lin_len; + int i, c; + + str_len = strlen(str); + sub_len = strlen(sub); + lin_len = strlen(lin); + + if ((str_len > 0) && (lin_len > 0)) { + if (casesense == false) { + l = nasm_strdup(lin); + for (i = 0; i < lin_len; i++) { + l[i] = (char)nasm_tolower_tab[(int)l[i]]; + } + ls = nasm_strdup(str); + for (i = 0; i < str_len; i++) { + ls[i] = (char)nasm_tolower_tab[(int)ls[i]]; + } + temp1 = l; + temp2 = ls; + } else { + l = lin; + ls = (char *)str; + } + + lt = l; + + do { + l = strstr(l, ls); + if (l != NULL) { + count ++; + l += str_len; + } + } while (l != NULL); + + if (count > 0) { + i = (lin_len - (count * str_len)); + i += (count * sub_len); + outline = nasm_zalloc(i); + + l = lt; + + for (i = 0; i < count; i ++) { + lp = l; + l = strstr(l, ls); + c = (lp - l); + if (c > 0) { + strncat(outline, lt, c); + } + strncat(outline, sub, sub_len); + l += str_len; + lt += str_len; + } + + c = (l - lin); + if (c < lin_len) { + strcat(outline, lt); + } + + if (temp2 != NULL) { + nasm_free(temp2); + } + + if (temp1 != NULL) { + nasm_free(temp1); + } + + nasm_free(lin); + } + } + + return outline; +} + #define lib_isnumchar(c) (nasm_isalnum(c) || (c) == '$' || (c) == '_') #define numvalue(c) ((c)>='a' ? (c)-'a'+10 : (c)>='A' ? (c)-'A'+10 : (c)-'0') diff --git a/nasmlib.h b/nasmlib.h index 2c335e11..12f9ca12 100644 --- a/nasmlib.h +++ b/nasmlib.h @@ -205,6 +205,11 @@ int nasm_memicmp(const char *, const char *, size_t); char *nasm_strsep(char **stringp, const char *delim); #endif +/* + * Replace all instances of `str` with `sub` in `lin` + */ +char *nasm_strrep(const char *str, const char *sub, char *lin, bool casesense); + /* * Convert a string into a number, using NASM number rules. Sets -- 2.11.4.GIT