Skip to content

StrFind

Description

Find the first occurrence of key inside s and return a pointer into s’s buffer.

Three call shapes via OVERLOAD + _Generic on key: StrFind(s, key)key is Str * or Zstr. StrFind(s, key, key_len)key is a fixed-length view (Zstr, size). Differs from StrIndexOf (which returns a size index); this returns a Zstr pointer into s’s storage at the match.

Parameters

Name Direction Description
s in Str to search in.
key in Substring to search for (Str * / Zstr).
key_len in Length of key when using the 3-arg fixed-length form.

Success

Returns a Zstr pointing at the first match inside s. The string is not modified.

Failure

Returns NULL when no match is found. The string is not modified.

Usage example (Cross-references)

Usage examples (Cross-references)
    // Test string find functions
    bool test_str_find(void) {
        WriteFmt("Testing StrFind variants\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        // Test StrFind (Str * key) with match at end
        Zstr found1 = StrFind(&haystack, &needle1);
        bool result = (found1 != NULL && ZstrCompare(found1, "World") == 0);
    
        // Test StrFind (Str * key) with match at beginning
        Zstr found2 = StrFind(&haystack, &needle2);
        result      = result && (found2 != NULL && ZstrCompare(found2, "Hello World") == 0);
    
        // Test StrFind (Str * key) with no match
        Zstr found3 = StrFind(&haystack, &needle3);
        result      = result && (found3 == NULL);
    
        // Test StrFind (Zstr key)
        Zstr found4 = StrFind(&haystack, "World");
        result      = result && (found4 != NULL && ZstrCompare(found4, "World") == 0);
    
        // Test StrFind (Cstr key, key_len)
        Zstr found5 = StrFind(&haystack, "Wor", 3);
        result      = result && (found5 != NULL && ZstrCompareN(found5, "World", 3) == 0);
    // corrupted s must abort before StrBegin(s) is read (Str.Mutants5).
    static bool test_str_find_str_corrupt_s_aborts(void) {
        WriteFmt("Testing StrFind validates s (should abort)\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        MAGIC_MARK_DIRTY(&s);
    
        (void)StrFind(&s, &key); // should abort here
    
        return false;            // unreachable on real code
    // (Str.Mutants5).
    static bool test_str_find_str_corrupt_key_aborts(void) {
        WriteFmt("Testing StrFind validates key (should abort)\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        MAGIC_MARK_DIRTY(&key);
    
        (void)StrFind(&s, &key); // should abort here
    
        return false;            // unreachable on real code
        s.__magic = 0;
    
        (void)StrFind(&s, "x", (size)1);
    
        DefaultAllocatorDeinit(&alloc);
Last updated on