Extracting string from char array specified by prefix and suffix

the following proposed code:

  1. assumes that the ‘output[]’ array is long enough to hold the result+1
  2. assumes that the ‘output[]’ is not to include the strings ‘start[]’ nor ‘end[]’

Caveat: this is not tested

Caveat: the resulting char array in ‘output[]’ is not NUL terminated so the calling code (probably) should pre initialize that array to all ‘\0’

void extract_string(char input[], char output[], char start[], end[])
{
    char *startPos = strstr( input, start );
    if( !startPos )
    {
        fprintf( stderr, " %s not found in %s\n", start, input );
        return;
    }

    startPos += strlen( start );

    char *stopPos = strstr( startPos, end );
    if( !stopPos )
    {
        fprintf( stderr, " %s not found in %s\n", end, startPos );
        return;
    }

    memcpy( output, startPos, stopPos - startPos +1 );
} // end function: extract_string

Leave a Comment