抓取“A =”和“&”之间的值但即使是“&”不在那里

时间:2017-05-30 15:42:42

标签: c

下面的脚本将提取

之间的值

A = &

但是如果“&”不存在..然后它将无法提取

之后的内容

A =

如何解决这个问题?

剧本:

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char *s = "A=apple&";

    const char *PATTERN1 = "A=";
    const char *PATTERN2 = "&";

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

1 个答案:

答案 0 :(得分:2)

当我们发现end时,这样:

end = strstr( start, PATTERN2 )

然后,如果它为null,我们目前什么都不做。我们应该将end设置为指向输入字符串的终止NUL,而不是什么都不做:

if (!end)
    end = start + strlen(start);

然后我们可以像以前一样复制:

target = malloc(end - start + 1);
memcpy(target, start, end - start);
target[end - start] = '\0';

(注意:我删除了malloc()

的无用且有害的演员阵容

完整的例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    const char *s = "A=apple&";

    const char *const PATTERN1 = "A=";
    const char *const PATTERN2 = "&";

    char *start = strstr(s, PATTERN1);
    if (!start) {
        printf("%s not found", PATTERN1);
        return EXIT_FAILURE;
    }

    start += strlen(PATTERN1);
    char *end = strstr(start, PATTERN2);
    if (!end)
        end = start + strlen(start);
    char *target = malloc(end - start + 1);
    memcpy(target, start, end - start);
    target[end - start] = '\0';

    printf("%s\n", target);

    free(target);

    return EXIT_SUCCESS;
}