且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C中的两个字符串之间查找文本

更新时间:2023-02-12 18:43:50

以下是如何执行此操作的生动示例

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;
}

输出为

TEXT TO EXTRACT