笔试题: 不使用中间变量求const字符串长度,即实现求字符串长度库函数strlen函数

来源:互联网 发布:qq视频聊天录像软件 编辑:程序博客网 时间:2024/04/29 17:54

笔试题:

不使用中间变量求const字符串长度,即实现求字符串长度库函数strlen函数。

函数接口声明如下:int my_strlen(const char *p);


strlen函数实际完成的功能是从代表该字符串的第一个地址开始遍历,直到遇到结束符'\0'。

而返回的长度大小不包括'\0'。

#include <stdio.h>#include <assert.h>//使用中间变量//int my_strlen(const  char *str)//{//   assert(str);//   int count = 0;//   while (*str++)//   {//       count++;//   }//   return count;// }//递归方法(不使用中间变量)int my_strlen(const char *str){if (*str == '\0'){return 0;}else{return 1 + my_strlen(str + 1);}}int main(){char str[] = {0};gets(str);int len = my_strlen(str);printf("%d\n", len);system("pause");return 0;}


wKioL1ZDSiaSCUhhAAApZBzGzpw986.png


0 0
原创粉丝点击