实现memstr请指正

/*
 * author:maolingzhi
 * date:2012-04-05
 * 这个程序是用来测试memstr用以模板strstr功能
 * mem*系列有memchr但是没有memstr,本程序用来实现该功能
 * SYNOPSIS
 * #include <string.h>
 * void *memstr(const void *s, const char *str, size_t n);
 * DESCRIPTION
 *        The  memstr()  function  scans  the first n bytes of the memory area pointed to by s for the string str.  The x byte to match str (interpreted as an unsigned
 *               character) stops the operation.
 * RETURN VALUE
 *       The memstr() functions return a pointer to the matching byte or NULL if the character does not occur in the given memory area.
 */

#include <stdio.h>
#if dev
#include <assert.h>
#endif
#include <string.h>
char *memstr(const char *s , const char *str , size_t n)
{
    if(NULL == s)
    {
        fprintf(stderr,"输入参数s为NULL!");
        return NULL;
    }

    if(NULL == str)
    {
        fprintf(stderr,"输入参数str为NULL!");
        return NULL;
    }

    if(n <= 0)
    {
        fprintf(stderr,"输入参数n为非正数!");
        return NULL;
    }

    if(strlen(str) == 0)
    {
        fprintf(stderr,"输入参数str为空!");
        return NULL;
    }

    char *_s = (char*)s;
    int _n = n;
    char *r = NULL;
   
    while(_n > 0 && ((r =(char*) memchr(_s,*str,_n)) != NULL) )
    {
        int distance = r - _s;
        if((distance  + strlen(str) <= _n) && (memcmp(r,str,strlen(str)) == 0))
        {
            return r;
        }
        else
        {
            _s = r+1;
            _n -= distance + 1;
        }
    }
    return NULL;

   }

#if dev
int main(void)
{
    {
    char a[] = "welc\r\nome";
    char str[] = "\r\n";
    char *p = memstr(a,str,strlen(a));
    assert(p == a+4);
    }

    {
    char a[] = "welcome\r\n";
    char str[] = "\r\n";
    char *p = memstr(a,str,strlen(a));
    assert(p == a+7);
    }

    {
    char a[] = "welcome\r";
    char str[] = "\r\n";
    char *p = memstr(a,str,strlen(a));
    assert(p == NULL);
    }


    {
    char a[] = "abab";
    char str[] = "b";
    char *p = memstr(a,str,strlen(a));
    assert(p == a+1);
    }


    return 0;
}
#endif

你可能感兴趣的:(实现)