C语言实现库函数中的strstr查找字符串中的子串的功能

自己使用C语言实现的库函数中的strstr函数的功能:代码如下 

#include 

static const char *strstr_t(const char *str, const char *sub_str)
{   
    const char *str_local = NULL;
    const char *sub_str_local = NULL;

    if(!str || !sub_str)
    {   
        printf("fun:%s param is error\n", __FUNCTION__);
        return NULL;
    }

    while(*str)
    {
        str_local = str;
        sub_str_local = sub_str;

        do
        {
            if(*sub_str_local == '\0')
            {   
                return str;
            }
        }while(*str_local++ == *sub_str_local++);
        str += 1;
    }
    
    return NULL;
}

int main(int argc, char **argv)
{
    int i = 0;
    char *str = NULL;
    char *sub_str = NULL;
    const char *sub = NULL;

    printf("input param:\n");
    for(i = 1; i < argc; i++)
    {
        printf("argv[%d]:%s\n", i, argv[i]);
    }

    str = argv[1];
    sub_str = argv[2];

    sub = strstr_t(str, sub_str);
    if(sub)
    {
        printf("sub string:%s\n", sub);
    }
    else
    {
        printf("error\n");
    }

    return 0;
}

代码测试如下:

study$ ./strstr_T.o 12345678 567
input param:
argv[1]:12345678
argv[2]:567
sub string:5678

 

 

你可能感兴趣的:(C语言,算法逻辑)