欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

从字符串中获取指定字符串之间字符串

程序员文章站 2022-03-08 11:57:11
...

从字符串中获取指定字符串之间字符串

/*从字符串"This is a test string"中获取"a "到" string"之间的字符串*/
#include <stdio.h>
#include <string.h>
char *get_timestr_from_json(char *src)
{
    printf("The get_timestr_from_json start!\r\n");
    char *target = NULL;
    char dest[100] = {0};
    char *p1, *p2;
    p1 = strstr(src, "a ");
    p2 = strstr(src, " string");
    while (p1 != NULL && p2 != NULL && p1 > p2)
    {
        p2++;
        p2 = strstr(p2, " string");
    }
    if (p1 == NULL || p2 == NULL || p1 > p2)
    {
        printf("Not found\n");
    }
    else
    {
        p1 += strlen("a ");
        memcpy(dest, p1, p2 - p1);
        target = dest;
    }
    printf("The get_timestr_from_json over!\r\n");
    return target;
}

int main()
{
    char *src = "This is a test string";
    char *time_str = NULL;
    time_str = get_timestr_from_json(src);
    if (time_str)
    {
        printf("%s\n",time_str);
    }
    return 0;
}

演示

从字符串中获取指定字符串之间字符串