strlen函数是用来计算字符串长度的,字串末尾’\0’不计入字串长度。
strlen函数实现:
1.原型:
#include <string.h>
size_t strlen(const char *s);
2.参数:
s:需要计算长度的字符串地址
3.实现一:
size_t my_strlen(const char *s)
{
const char *p = s;
//参数判断
if(NULL == s){
return -1;
}
//查找字符串末尾
while(*p++){
//do nothing
}
return ((int)(p - s - 1));
}
4.实现二(实现一改造下):
size_t my_strlen(const char *s)
{
const char *p = s;
//参数判断
if(NULL == s){
return -1;
}
//查找字符串末尾
while(*p){
++p;
}
return ((int)(p - s));
}
==============本文完结================
小菜总结,如有不当,欢迎批评!