strlen函数实现的两种方法
①使用变量(在函数中定义变量来计算字符串的长度)
#include <stdio.h>
int mystrlen(const char *p)
{
int sum = 0;
while(*p)
{
sum++;
p++;
}
return sum;
/*或者
char *tem = p;
while(*p++);
return p-tem;
*/
}
int main()
{
char *p = "";
printf("%d\n", mystrlen(p));
}
②不使用函数且不在函数中定义变量(编程思想:递归)
#include <stdio.h>
int mystrlen(const char *p)
{
if(*p == 0)return;
return mystrlen(p+1)+1;
}
int main()
{
printf("%d\n", mystrlen("asdfsdfasdsdf"));
}
当然如果要求仅为不能定义变量,还可以使用库函数中的strlen函数进行计算。