diff --git a/src/std/c_string.c b/src/std/c_string.c index 89d9a099a..2c744758d 100644 --- a/src/std/c_string.c +++ b/src/std/c_string.c @@ -120,3 +120,26 @@ void c_strlist_destroy(c_strlist_t *strlist) { SAFE_FREE(strlist); } +char *c_strreplace(char *src, const char *pattern, const char *repl) { + char *p = NULL; + + while ((p = strstr(src, pattern)) != NULL) { + size_t of = p - src; + size_t l = strlen(src); + size_t pl = strlen(pattern); + size_t rl = strlen(repl); + + if (rl > pl) { + src = (char *) c_realloc(src, strlen(src) + rl - pl + 1); + } + + if (rl != pl) { + memmove(src + of + rl, src + of + pl, l - of - pl + 1); + } + + strncpy(src + of, repl, rl); + } + + return src; +} + diff --git a/src/std/c_string.h b/src/std/c_string.h index 93b9bd328..a6d4efdec 100644 --- a/src/std/c_string.h +++ b/src/std/c_string.h @@ -105,6 +105,19 @@ int c_strlist_add(c_strlist_t *strlist, const char *string); */ void c_strlist_destroy(c_strlist_t *strlist); +/** + * @breif Replace a string with another string in a source string. + * + * @param src String to search for pattern. + * + * @param pattern Pattern to search for in the source string. + * + * @param repl The string which which should replace pattern if found. + * + * @return Return a pointer to the source string. + */ +char *c_strreplace(char *src, const char *pattern, const char *repl); + /** * }@ */ diff --git a/tests/std_tests/check_std_c_str.c b/tests/std_tests/check_std_c_str.c index d268a437d..024c0325c 100644 --- a/tests/std_tests/check_std_c_str.c +++ b/tests/std_tests/check_std_c_str.c @@ -96,12 +96,24 @@ START_TEST (check_c_strlist_expand) } END_TEST +START_TEST (check_c_strreplace) +{ + char *str = c_strdup("/home/%(USER)"); + + str = c_strreplace(str, "%(USER)", "csync"); + fail_unless(strcmp(str, "/home/csync") == 0, NULL); + + SAFE_FREE(str); +} +END_TEST + static Suite *make_std_c_strlist_suite(void) { Suite *s = suite_create("std:str:c_stringlist"); create_case(s, "check_c_strlist_new", check_c_strlist_new); create_case(s, "check_c_strlist_add", check_c_strlist_add); create_case(s, "check_c_strlist_expand", check_c_strlist_expand); + create_case(s, "check_c_strreplace", check_c_strreplace); return s; }