C语言:递归和非递归分别实现strlen求字符串长度。

字符串存放时,最后一位是\0。所以在求字符串长度的时候,只需要判断当前地址是否为\0,如果不是,地址+1,获取下一个字符。就可以知道长度。

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include "stdlib.h"
#include<stdio.h>
//非递归方法,当首地址元素不是0的时候,首地址会+1,同时计数器也会加1,当到达最后一个字符时,值为0,返回计数结果
int my_strlen(char *string)
{
	int count = 0;
	while (*string)	
	{
		string++;
		count++;
	}
	return count;
}

int main()
{
	char *str = "abcdef";
	printf("%d\n", my_strlen(str));
	system("pause");
	return 0;
}

//递归方法,地址加1,并且每次返回值加1,当地址所对应的字符为0时,返回。
int my_strlen(char *string)
{
	if (*string == '\0')
	{
		return 0;
	}
	else
	{
		return 1 + my_strlen(string + 1);
	}
}
int main()
{
	char *str = "abcdef";
	printf("%d\n", my_strlen(str));
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43220266/article/details/83242012