GNOME Bugzilla – Bug 585816
GString doesn't have a g_string_replace() function
Last modified: 2018-05-24 11:53:18 UTC
eg: replace all "12" in "125671289312345" with "ab" or "a" or "abcd" my patches: (one to gstring.h, one to gstring.c in glib-2.20.0, code tested.) --- gstring.h 2009-03-13 12:09:59.000000000 +0800 +++ gstring.h2 2009-06-15 15:40:48.000000000 +0800 @@ -119,6 +119,9 @@ GString* g_string_erase (GString *string, gssize pos, gssize len); +GString* g_string_replace (GString *string, + const gchar *sub, + const gchar *repl); GString* g_string_ascii_down (GString *string); GString* g_string_ascii_up (GString *string); void g_string_vprintf (GString *string, --- gstring.c 2009-06-15 15:41:25.000000000 +0800 +++ gstring.c2 2009-06-15 15:41:00.000000000 +0800 @@ -1219,6 +1219,69 @@ } /** + * g_string_replace: + * @string: a #GString + * @sub: the substring target in #GString, to be replaced. + * @repl: the third string to replace sub. + * + * Replaces all instances of @sub from a #GString with @repl. + * if @sub is empty or no instance found in #GString, nothing will happen. + * if @repl is empty, it will erase all @sub (s) in #GString. + * + * Returns: @string + */ +GString* +g_string_replace (GString *string, + const gchar *sub, + const gchar *repl) +{ + gsize ls, lr; + gchar *q, *t; + + g_return_val_if_fail (string != NULL, NULL); + g_return_val_if_fail (sub != NULL, NULL); + g_return_val_if_fail (repl != NULL, NULL); + + q = string->str; + ls = strlen(sub); + lr = strlen(repl); + + if (!ls) + goto end; + + if(ls > lr) { + while(*q != '\0' && (t = strstr(q,sub)) != NULL) { + memcpy(t, repl, lr); + strcpy(t+lr, t+ls); + q = t + lr; + string->len -= ls-lr; + } + } else if(ls == lr) { + while(*q != '\0' && (t = strstr(q,sub)) != NULL) { + memcpy(t, repl, lr); + q = t + lr; + } + } else { + while(*q != '\0' && (t = strstr(q,sub)) != NULL) { + ptrdiff_t offt, offq; + + offq = q - string->str; + offt = t - string->str; + g_string_maybe_expand(string, lr-ls); + q = string->str + offq; + t = string->str + offt; + g_memmove(t+lr, t+ls, strlen(t+ls)+1); + memcpy(t, repl, lr); + q = t + lr; + string->len += lr-ls; + } + } + +end: + return string; +} + +/** * g_string_ascii_down: * @string: a GString *
Created attachment 136607 [details] [review] patch to gstring.c in glib-2.20.0
Created attachment 136608 [details] [review] patch to gstring.h in glib-2.20.0
I'm reluctant to agree with this kind of additions, since string functions are like lemmings... there's so many of them, and they are all very similar. Its a slippery slope; once we add this, surely people will want a regex replace version...
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/glib/issues/225.