Skip to content

StrStrip

Description

Strip leading and trailing characters from s, returning a new Str. The original s is unmodified. The returned Str owns its storage and must be deinited after use.

Parameters

Name Direction Description
s in Str to strip.
chars_to_strip in Optional Zstr listing characters to strip. NULL strips standard ASCII whitespace.

Success

Returns a new Str with surrounding characters removed. s is not modified.

Failure

Returns a zero-length Str when the whole input strips away or on allocator OOM.

Usage example (Cross-references)

Usage examples (Cross-references)
    
        if (StrLen(value) > 0) {
            Str stripped = StrStrip(value, NULL);
            StrDeinit(value);
            *value = stripped;
    // Test string strip functions
    bool test_str_strip(void) {
        WriteFmt("Testing StrStrip variants\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        // Test StrStrip
        stripped = StrStrip(&s1, NULL);
        result   = result && (ZstrCompare(StrBegin(&stripped), "Hello") == 0);
        StrDeinit(&stripped);
        StrDeinit(&stripped);
    
        stripped = StrStrip(&s1, "*");
        result   = result && (ZstrCompare(StrBegin(&stripped), "Hello") == 0);
        StrDeinit(&stripped);
    // `end == start`; intact keeps it (len 1), the mutant drops it (len 0).
    static bool test_strip_single_surviving_char_kept(void) {
        WriteFmt("Testing StrStrip keeps a lone surviving char\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        Str  s        = StrInitFromZstr("x", &alloc);
        Str  stripped = StrStrip(&s, "*");
        bool result   = (StrLen(&stripped) == 1) && (ZstrCompare(StrBegin(&stripped), "x") == 0);
    // corrupted magic word must abort at the validation barrier (Str.Mutants6).
    static bool test_strip_str_corrupt_magic_aborts(void) {
        WriteFmt("Testing StrStrip aborts on corrupt magic\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        Str s                     = StrInitFromZstr("  x  ", &alloc);
        GENERIC_VEC(&s)->__magic ^= 0x1;
        Str stripped              = StrStrip(&s, NULL);
    
        StrDeinit(&stripped);
Last updated on