常用字符串函数实现

1、memcpy函数

void* memcpy(void *dest,const void *src,int n)
{
    if(NULL == dest||NULL ==src)
    {
        return  NULL ;
    }

    char * tdest = (char*)dest;//save the start adress
    char * tsrc =  (char*)src;
    if(tsrc< tdest && tsrc + n >=tdest)//address  repeat
    {
        tdest +=n;//move to the end
        tsrc += n;
        while(n--)//copy from high to low
        {
            *tdest-- =  (char)*tsrc--;
        }
    }else
    {
        while (n--)
        {
            *tdest++  =  (char)*tsrc++;
        }
    }
    
    return  (void*)dest;
}

2、strcat函数

char* strcat(char* dest,const char* src)
{
    if(NULL == dest||NULL ==src)
    {
        return  NULL ;
    }

    char* tdest = dest;
    const char* tsrc = src;
    while (*tdest!= '\0') tdest++ ;//move to the lastest location
    
    while(*tsrc!= '\0')//copy
    {
        *tdest++ = *tsrc++;
    }

   * tdest = '\0';//set the end flag

    return dest;
}

3、strcpy函数

char* strcpy(char* dest,const char* src)
{
    if(NULL == dest||NULL ==src)
    {
        return  NULL ;
    }

    char* tdest = dest;
    const char* tsrc = src;
    while ((*tdest++ = *tsrc++) != '\0');
   
    return dest;
}

4、strcmp函数

int strcmp(const char *str1,const char *str2)
{
    if(NULL == str1||NULL == str2)
    {
        return -1;
    }

    while(*str1 !='\0' && *str2 != '\0')
    {
        if(0 == (*str1 - *str2)) //相同则指针后移
        {
            str1++;
            str2++;
            continue;
        }
        else//不同则返回差值
        {
            return (*str1 - *str2);
        }    
    }

    return  (*str1 - *str2);
}
int strcmp1(const char *str1,const char *str2)
{
    assert(str1&&str2);
    while(*str1&&(*str1++ == *str2++));

    return  (*str1 - *str2);
}

你可能感兴趣的:(C/C++,算法)