C语言递归和非递归分别实现strlen

C语言递归和非递归分别实现strlen

1.非递归的方法实现strlen

int mystrlen(char* buf) {
	int count = 0;
	while (*buf != '\0') {
		count++;
		*buf++;
	}
	return count;
}
int main() {
	char buf[] = "welcome to bit";
	int ret = mystrlen(buf);
	printf("%d\n",ret);
	system("pause");
	return 0;
}

2.用递归的方法实现strlen

int mystrlen2(char* buf) {
	if (*buf == '\0') {//*buf即提取当前buf的地址中的元素
		return 0;
	}
	return 1 + mystrlen2(buf + 1);
}
int main() {
	char buf[] = "welcome to bit";
	int ret = mystrlen2(buf);
	printf("%d\n", ret);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a_hang_szz/article/details/88846193