自己实现c常见字符串函数

1.strlen()

int my_strlen(const char *s)
{
     int len=0;
     if(s==NULL)
     {
        printf("error: null pointer...\n");
        len=-1;
        goto end;
     }
     while(*s++!='\0')
     {
          len++;
     }
  end:
      return len;
}

2.strcpy()

char *my_strcpy(char *dest,const char *src)
{
    char *tmp=dest;
    if(dest==NULL||src==NULL)
    {   
        printf("error: null pointer...\n");
        tmp=NULL;
        goto end;
    }
    while((*dest++ = *src++)!='\0');  //不考虑溢出
end:
    return tmp;
}

3.strcat()

char *my_strcat(char *dest,const char *src)
{
    char *tmp=dest;
    if(dest==NULL||src==NULL)
    {
        printf("error: null pointer...\n");
        tmp=NULL;
        goto end;
    }
    while(*(++dest) != '\0'); //指向目标字符串的结尾空字符
    while((*dest++ = *src++) != '\0');
end:
    return tmp;
}

4.strcmp()

char my_strcmp(const char *s1,const char s2)  //其实就是返回第一个不相等的字符的ASCII码差值
{
    char value=0;
    if(s1==NULL||s2==NULL)
    {
        printf("error: null pointer...\n");
        value=-128;
        goto end;
    }
    while(*s1!='\0' && *s2!='\0' && (value=*s1-*s2)==0) //逐个字符比较,如果没比较还没进行到末尾且当前比较的两个字符相等,则继续比下去
    {
         s1++;
         s2++;
    }
    if(value==0 && !(*s1==0 && *s2==0))  //考虑s1包含s2或s2包含s1的情况
    {
         value=*s1-*s2;
    }
end:
    return value;
}

5.strchr()

char *my_strchr(const char *src,char ch)
{
    if(src==NULL)
    {
        printf("error: null pointer...\n");
        return NULL;
    }   
    while(*src++ != '\0')
    {
        if(*src==ch)
        {
            return src;
        }
    }
} 

6.strstr()

char *my_strstr(const char *s1,const char *s2)
{
    if(s1==NULL||s2==NULL)
    {
        printf("error: null pointer...\n");
        goto end;
    }
    while(*s1++ != '\0')  //长字符串只需一轮遍历
    {
        char *s1_tmp=s1;
        char *s2_tmp=s2;
        int flag=0;
        while(*s1_tmp++!='\0'&&*s2_tmp++!='\0')
        {
             if(*s1_tmp!=*s2_tmp)  //每小轮比较中,如果对应有字符不相等,则标记
             {
                 flag=1;
             }
        }
        if(flag==0 && *s2_tmp=='\0')  //如果小字符串遍历了且没有标记,说明找到了相等的子字符串
        {
             return s1;
        }
    }
end:
    return NULL;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值