//递归和非递归分别实现strlen
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//非递归
//int my_strlen(char* str)
//{
// assert(str != NULL);
//
// int count = 0;
//
// while (*str != '\0')
// {
// str++;
// count++;
// }
//
// return count;
//}
//递归方法
int my_strlen(char*str)
{
if (*str != '\0')
{
return 1+my_strlen(str+1);
}
else
{
return 0;
}
}
int main()
{
char str[10] = "abcde";
printf("%d",my_strlen(str));
system("pause");
return 0;
}
注意递归时的else语句不能丢,不然会使函数一直递归,加了之后在不满足if条件时返回上一层递归。