笔试面试5 实现C库函数strlen

来源:互联网 发布:java观察者模式 代码 编辑:程序博客网 时间:2024/05/29 13:48

这是个非常简单的问题。

strlen(str)就是计算str一共有多少个字符。

而字符串存放的时候,会在最后一个字符的后面加一个'\0'。

利用这个即可编写自己的strlen函数。

源码:

#include<stdio.h>#include <conio.h>int MyStrlen(char str[]){if(str==NULL)//判断str是否有效  return 0;int counts=0;//直接以counts作为计数器while(str[counts++]!='\0')           ;return counts-1;}int main(){ char str1[]="hello";//5char *str2="OK";//2char *str3="";//0char *str4;//0printf("str1=%s\n",str1);printf("strlen(str1)=%d\n",MyStrlen(str1));printf("str2=%s\n",str2);printf("strlen(str2)=%d\n",MyStrlen(str2));printf("str3=%s\n",str3);printf("strlen(str3)=%d\n",MyStrlen(str3));printf("str4=%s\n",str4);printf("strlen(str4)=%d\n",MyStrlen(str4)); getch();  }

测试结果:




——————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:coderguang@gmail.com

2014-11-5

于GDUT

——————————————————————————————————————————————————————————————————




0 0
原创粉丝点击