StrResize

Table of Contents

StrResize

Description

Resize string. If length is smaller than current capacity, string length is shrinked. If length is greater than current capacity, space is reserved and string is expanded.

Parameters

NameDirectionDescription
vecin,outStr to be resized.
leninNew length of string.

Success

return

Failure

Does not return

Usage example (Cross-references)

    // Test StrResize function
    bool test_str_resize(void) {
    printf("Testing StrResize\n");
    
    Str s = StrInitFromZstr("Hello");
    
    // Resize to a smaller length
    StrResize(&s, 3);
    
    // Length should now be 3 and content should be "Hel"
    
    // Resize to a larger length
    StrResize(&s, 8);
    
    // Length should now be 8, and the first 3 characters should still be "Hel"
    // But StrForeachInRangeIdx will continue until idx reaches original_length (12)
    if (idx == 4) {
    StrResize(&s, 3); // Shrink to only 3 characters
    printf(
    "String resized to length %zu, but range iteration will continue to idx %zu...\n",
    // but the string length is now smaller
    if (idx == 10) {
    StrResize(&s, 4); // Shrink to only 4 characters
    printf("String resized to length %zu during reverse iteration...\n", s.length);
    }
    // This will make the current idx invalid after the body executes
    if (idx == 4) {
    StrResize(&s, 4); // Shrink to only 4 characters (valid indices: 0,1,2,3)
    printf("String resized to length %zu, current idx=%zu is now out of bounds...\n", s.length, idx);
    }
    // When we reach idx=12, shrink the string significantly
    if (idx == 12) {
    StrResize(&s, 5); // Shrink to only 5 characters
    printf("String resized to length %zu during reverse ptr iteration...\n", s.length);
    }
    // This will make subsequent iterations invalid
    if (idx == 3) {
    StrResize(&s, 2); // Shrink to only 2 characters
    printf("String resized to length %zu, but basic foreach iteration continues...\n", s.length);
    }

Share :