Skip to content

StrReplace

Description

Replace occurrences of match in s with replacement.

Three call shapes via OVERLOAD + _Generic on match: StrReplace(s, match, replacement, count)match and replacement are both Str * or both Zstr. StrReplace(s, match, match_len, replacement, replacement_len, count)match / replacement are fixed-length views (Zstr, size). count = -1 requests replace-all; otherwise at most count occurrences are replaced.

Parameters

Name Direction Description
s in,out Str to modify in place.
match in Pattern to find (Str * / Zstr).
match_len in Length of match for the 6-arg form.
replacement in Replacement bytes (Str * / Zstr).
replacement_len in Length of replacement for the 6-arg form.
count in Maximum number of replacements; -1 for all.

Success

Modifies s in place. Returns no value.

Failure

s is left unchanged when match does not occur in s.

Usage example (Cross-references)

Usage examples (Cross-references)
    // Test string replace functions
    bool test_str_replace(void) {
        WriteFmt("Testing StrReplace variants\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        // Test Zstr-form (string literals)
        Str s1 = StrInitFromZstr("Hello World", &alloc);
        StrReplace(&s1, "World", "Universe", 1);
        bool result = (ZstrCompare(StrBegin(&s1), "Hello Universe") == 0);
        StrDeinit(&s1);
        s1 = StrInitFromZstr("Hello Hello Hello", &alloc);
        StrReplace(&s1, "Hello", "Hi", 2);
        result = result && (ZstrCompare(StrBegin(&s1), "Hi Hi Hello") == 0);
        StrDeinit(&s1);
        s1 = StrInitFromZstr("Hello World", &alloc);
        StrReplace(&s1, "World", 5, "Universe", 8, 1);
        result = result && (ZstrCompare(StrBegin(&s1), "Hello Universe") == 0);
        Str find    = StrInitFromZstr("World", &alloc);
        Str replace = StrInitFromZstr("Universe", &alloc);
        StrReplace(&s1, &find, &replace, 1);
        result = result && (ZstrCompare(StrBegin(&s1), "Hello Universe") == 0);
Last updated on