Skip to content
StrForeachInRangeIdx

StrForeachInRangeIdx

Description

Walk characters of str in the half-open range [start, end), binding chr to the character value at index idx. Both chr and idx are stamped by the macro. See VecForeachInRangeIdx for the full SUCCESS/FAILURE contract.

Usage example (Cross-references)

Usage examples (Cross-references)
    // Test StrForeachInRangeIdx macro
    bool test_str_foreach_in_range_idx(void) {
        WriteFmt("Testing StrForeachInRangeIdx\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        // Build a new string by iterating through a range of characters with indices
        Str result = StrInit(&alloc);
        StrForeachInRangeIdx(&s, chr, idx, 6, 11) {
            // Append the character and its index to the result string
            StrAppendFmt(&result, "{c}{}", chr, idx);
        // Test with empty range
        Str empty_result = StrInit(&alloc);
        StrForeachInRangeIdx(&s, chr, idx, 3, 3) {
            // This block should not execute
            StrPushBackR(&empty_result, chr);
    // Make idx go out of bounds in StrForeachInRangeIdx by shrinking string during iteration
    bool test_str_foreach_out_of_bounds_access(void) {
        WriteFmt("Testing StrForeachInRangeIdx where idx goes out of bounds\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        // Even if we shrink the string, the loop will continue until idx reaches the fixed end
        size original_length = StrLen(&s); // Capture this as 12
        StrForeachInRangeIdx(&s, chr, idx, 0, original_length) {
            WriteFmt("Accessing idx {} (s.length={}): '{c}'\n", idx, StrLen(&s), chr);
    // Make idx go out of bounds in StrForeachInRangeIdx by deleting characters
    bool test_str_foreach_idx_out_of_bounds_access(void) {
        WriteFmt("Testing StrForeachInRangeIdx with character deletion where idx goes out of bounds\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        // when we delete characters during iteration
        size original_length = StrLen(&s); // Capture this as 11
        StrForeachInRangeIdx(&s, chr, idx, 0, original_length) {
            WriteFmt("Accessing idx {} (s.length={}): '{c}'\n", idx, StrLen(&s), chr);
Last updated on