字符串函数构析

字符串函数构析

今日参加了一场笔试,刚好程序题问到一道strcpy函数构建,刚好之前看过字符串函数,同时网上文章大部分都是介绍了下函数的用法,缺少了函数的实现,今日就来自己构析下常见的字符串函数,字符串函数位于标准库的头文件string.h中,在使用函数时需引用该文件

strlen

  • 函数原型:size_t strlen(const char *s)

  • 函数功能:返回s的字符串函数(不包含结尾的0)

  • 函数构析:

     size_t strlen(const char *s)    /*size_t在不同架构下分别代表                              unsigned int和 unsigned long*/
     {
         int idx = 0;
         while(s[idx]!='\0')
         {
             idx++;
         }
         return idx;
     }

     

strcmp

  • 函数原型:int mycmp(const char *s1,const char *s2)

  • 函数功能:比较两字符串,返回值为三种结果(以ascii码表对比)

    • 0:s1==s2

    • 正数:s1>s2

    • 负数:s1<s2

  • 函数构析:

     int mycmp(char *s1,const char *s2)
     {
         while(*s1 == *s2 && *s1 != '\0')
         {
             s1++;
             s2++;
         }
             
         return *s1 - *s2;
      } 

     

strcpy

  • 函数原型:char *strcpy(char *dst,const char * src)

  • 函数功能:返回s的字符串函数(不包含结尾的0)

  • 函数构析:

     char *mycpy(char *dst,const char *src)
     {
         char *rest = dst;
         while(*dst++ = *src++);
             
         *dst='\0';
         return rest;
      } 

     

strcat

  • 函数原型:char *mycat(char *dst,const char * src)

  • 函数功能:返回s的字符串函数(不包含结尾的0)

  • 函数构析:

     char *mycat(char *s1,const char *s2)
     {
         char *rest = s1;
         s1 = s1 + strlen(s1);
         while(*s1++ = *s2++);
         
         return rest;
     }

     

 


 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值