C语言:strlen的递归与非递归实现

//递归和非递归分别实现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条件时返回上一层递归。

猜你喜欢

转载自blog.csdn.net/qq_43647265/article/details/86493022