如何在C中的两个字符串之间查找文本 [英] How to find text between two strings in c

查看:136
本文介绍了如何在C中的两个字符串之间查找文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提取c中2个字符串模式之间的文本.

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

示例:

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

PATTERN1=<BBBB>
PATTERN2=</BBBB>

谢谢.

推荐答案

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

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

这篇关于如何在C中的两个字符串之间查找文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆