【C语言】strlen的三种实现方法,strcmp,strcat,strcpy

    首先我们来看一下大家学习中经常熟悉用到的strlen函数。

    strlen 1:指针差值返回

int my_strlen(const char *str)
{
             char *pst = (char *)str;
            assert(str);
             while(*str)
            {
                        str++;
            }
             return  str - pst;
}

    strlen2:递归实现

int my_strlenT(const char *str)
{
            assert(str);
             if(*str)
                         return 1+my_strlenT(str+1);
             else
                         return 0;
}

    strlen3:计数器控制

int my_strlenO(const char *str)
{
             int count = 0;
            assert(str);
             while(*str++)
            {
                        count++;
            }
             return count;
}

    strcmp的书写:

    

int strcmp(const char *str, const char *Dstr)        //判断函数,不允许改变参数y
{
             int ret = 0;                     //定义返回值
            assert((str != NULL)&&(Dstr != NULL));        //判D断
             while(!(ret =*(unsigned char*)str - *( unsigned char *)Dstr) && Dstr)      
             //计算ret的值:o若??字符串的值相                                                        //同则为a0,大于为,小于为a-1;
            {
                        str++;                                //当判断字符串为时结束;
                        Dstr++;
            }
             if(ret < 0)
                        ret = -1;
             else if (ret > 0)
                        ret = 1;
             return ret;
}

    strcpy:

#include <stdio.h>
#include <assert.h>
char *my_strcpy(char *Dstr,char const *Sstr)
{          
             char *Astr = (char *)Dstr;
            assert((Dstr != NULL) && (Sstr != NULL));
             while((*Dstr = *Sstr) != '\0' )
            {
                        Dstr++;
                        Sstr++;
            }
             return Astr;
}

strcat:

char *my_strcat(char *Dstr,char const *Sstr)
{
             char *Astr = (char *)Dstr;
            assert((Dstr != NULL) && (Sstr != NULL));
             while('\0' != *Dstr)
                                    Dstr++;
            *Dstr = ' ';
            Dstr++;
             while('\0' != *Sstr)
            {
                        
                        *Dstr++ = *Sstr++;
            }
            *Dstr = '\0';
             return Astr;
}

好了,这篇博文就这样,写的都是一些我们常用的字符串操作函数,然后大家都注意一下assert和书写的简洁模式。恩,就这样

你可能感兴趣的:(strlen,strcat,strcpy,strcmp)