Search code examples
ccharsubstringc-stringsstrstr

How to find text between two strings in c


I need to extract the text between 2 string patterns in c.

Example:

aaaaaa<BBBB>TEXT TO EXTRACT</BBBB>aaaaaaaaa

PATTERN1=<BBBB>
PATTERN2=</BBBB>

Thanks.


Solution

  • Here is an alive example of how to do this

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        const char *s = "aaaaaa<BBBB>TEXT TO EXTRACT</BBBB>aaaaaaaaa";
    
        const char *PATTERN1 = "<BBBB>";
        const char *PATTERN2 = "</BBBB>";
    
        char *target = NULL;
        char *start, *end;
    
        if ( start = strstr( s, PATTERN1 ) )
        {
            start += strlen( PATTERN1 );
            if ( end = strstr( start, PATTERN2 ) )
            {
                target = ( char * )malloc( end - start + 1 );
                memcpy( target, start, end - start );
                target[end - start] = '\0';
            }
        }
    
        if ( target ) printf( "%s\n", target );
    
        free( target );
    
        return 0;
    }
    

    The output is

    TEXT TO EXTRACT