用三种方法实现strlen的功能

1.用遍历的方法实现。

(1).从首元素开始,遍历这个字符串只有不是'\0'就加一;

#include<stdio.h>
#include<stdlib.h>

int My_strlen(char* arr)
{
	int i = 0;
	while(*arr)//遍历整个字符串,直到'\0'结束
	{
		i++;
		arr++;
	}
	return i;
}
int main()
{
	char a[] = "asdffs";
	int s = My_strlen(a);
	printf("%d", s);
	system("pause");
	return 0;
}

2.用递归实现

(1)用递归的不断调用实现,当找到'\0'时返回0;

#include<stdio.h>
#include<stdlib.h>

int My_strlen(char* arr)
{
	if(*arr == '\0')//找到'\0'时结束,返回0;
	{
		return 0;
	}
	return 1+My_strlen(arr+1);
}
int main()
{
	char a[] = "asdffs";
	int s = My_strlen(a);
	printf("%d", s);
	system("pause");
	return 0;
}

3.用指针的方式实现

(1).首先定义一个指针指向首地址,然后找到这个字符串的末尾('\0'),并用指向末尾的指针减去首地址。

因为两个指针之差就是这两个指针之间元素的个数。

#include<stdio.h>
#include<stdlib.h>

int My_strlen(char* arr)
{
	char *q = arr;
	while(*arr)//找到‘\0’结束
		arr++;
	return arr - q;
}

int main()
{
	char a[] = "asdffs";
	int s = My_strlen(a);
	printf("%d", s);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ksaila/article/details/80284854