Skip to content

Commit

Permalink
Add 'ustring_replacing_char'
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanoBilenchi committed Mar 22, 2024
1 parent 3c87907 commit b32ac9a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions include/ustring.h
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,19 @@ UString ustring_join(UString const *strings, ulib_uint count, UString sep);
ULIB_API
UString ustring_repeating(UString string, ulib_uint times);

/**
* Returns a new string obtained by replacing all occurrences of a character with another.
*
* @param string String.
* @param needle Character to replace.
* @param replacement Replacement character.
* @return New string.
*
* @destructor{ustring_deinit}
*/
ULIB_API
UString ustring_replacing_char(UString string, char needle, char replacement);

/**
* Checks if the string does not contain lowercase characters.
*
Expand Down
12 changes: 12 additions & 0 deletions src/ustring.c
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,18 @@ UString ustring_repeating(UString string, ulib_uint times) {
return ret;
}

UString ustring_replacing_char(UString string, char needle, char replacement) {
ulib_uint const len = ustring_length(string);
UString ret;
char *buf = ustring(&ret, len);
if (!len) return ret;
memcpy(buf, ustring_data(string), len);
for (char *cur = buf; (cur = memchr(cur, needle, len - (cur - buf))) != NULL; ++cur) {
*cur = replacement;
}
return ret;
}

UString ustring_to_upper(UString string) {
UString ret;
ulib_uint const len = ustring_length(string);
Expand Down
3 changes: 3 additions & 0 deletions test/tests/ustring_tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,10 @@ bool ustring_test_base(void) {

a = ustring_repeating(ustring_literal("123"), 4);
utest_assert_ustring(a, ==, ustring_literal("123123123123"));
b = ustring_replacing_char(a, '3', '4');
utest_assert_ustring(b, ==, ustring_literal("124124124124"));
ustring_deinit(&a);
ustring_deinit(&b);

a = ustring_with_format("%d%d%d", 1, 2, 3);
utest_assert_ustring(a, ==, ustring_literal("123"));
Expand Down

0 comments on commit b32ac9a

Please sign in to comment.