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

#include <stdio.h>
#include <stdlib.h>
//递归实现strlen
int Strlen(char* str){
	if (str[0] == '\0'){
		return 0;
	}
	//str本质上是一个字符数组的首元素地址
	//str + 1就表示首元素的下一个元素(即次元素)地址
	return 1 + Strlen(str + 1);
}
//非递归实现strlen
int Strlen_N(char* str){
	int count = 0;	//用count来计数
	while (str[0] != '\0'){		//满足字符数组的首元素不是空字符,就进入循环
		++count;	
		++str;
	}
	return count;
}
int main(){
	char* str = "abcdef";
	printf("递归:%d\n",Strlen(str));
	printf("非递归:%d\n",Strlen_N(str));
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44781107/article/details/89188809