利用函数求字符串长度

80 阅读1分钟

求字符串长度确实可以简单粗暴的一个个去数,而字符串后面通常跟着的是\0这就方便我们停下就然后返回一个数值就是字符串长度,则就要传字符串地址去才能一个个访问。

#include<stdio.h>
int my_strlen(char*str)
{
	char*start=str;//指向arr首元素即b的地址 
	char*end=str;//++后一个个访问 
	while(*end!='\0') //字符串后面都带\0遇到\0就停止 
	{
		end++;
	}
	return end-start;
}
int main()
{
	char arr[]="bit";
	int str=0;
	str=my_strlen(arr);
	printf("%d\n",str);
	return 0;
 }

注意!!!

不能用char arr=‘bit’这样访问数组,因为这样的数组是常量不能被改变也不能访问。