Skip to content
StrForeachInRangeIdx

StrForeachInRangeIdx

StrForeachInRangeIdx

Description

Iterate over characters in a specific range of the given Str str at each index idx. This macro is a direct alias for VecForeachInRangeIdx specialized for Str. The variables chr and idx are declared and defined by the underlying macro.

Parameters

Name Direction Description
str in,out Str to iterate over.
chr in Name of variable to be used which’ll contain character at iterated index idx.
idx in Name of variable to be used for iterating over indices.
start in Starting index (inclusive).
end in Ending index (exclusive).

Usage example (Cross-references)

Usage examples (Cross-references)
                    if (start < end) {
                        size_t total_len = 0;
                        StrForeachInRangeIdx(str, ch, idx, start, end) {
                            total_len += 1 + idx;
                        }
    // Test StrForeachInRangeIdx macro
    bool test_str_foreach_in_range_idx(void) {
        WriteFmt("Testing StrForeachInRangeIdx\n");
    
        Str s = StrInitFromZstr("Hello World");
        // Build a new string by iterating through a range of characters with indices
        Str result = StrInit();
        StrForeachInRangeIdx(&s, chr, idx, 6, 11) {
            // Append the character and its index to the result string
            StrWriteFmt(&result, "{c}{}", chr, idx);
        // Test with empty range
        Str empty_result = StrInit();
        StrForeachInRangeIdx(&s, chr, idx, 3, 3) {
            // This block should not execute
            StrPushBack(&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");
    
        Str s = StrInitFromZstr("Hello World!"); // 12 characters
        // Even if we shrink the string, the loop will continue until idx reaches the fixed end
        size original_length = s.length; // Capture this as 12
        StrForeachInRangeIdx(&s, chr, idx, 0, original_length) {
            WriteFmt("Accessing idx {} (s.length={}): '{c}'\n", idx, s.length, 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");
    
        Str s = StrInitFromZstr("Programming"); // 11 characters
        // when we delete characters during iteration
        size original_length = s.length; // Capture this as 11
        StrForeachInRangeIdx(&s, chr, idx, 0, original_length) {
            WriteFmt("Accessing idx {} (s.length={}): '{c}'\n", idx, s.length, chr);
Last updated on