signed

QiShunwang

“诚信为本、客户至上”

求字符串长度——随手记

2021/6/3 18:28:04   来源:

突然想到中午视频上看到了的通过指针求字符串长度的内容,赶紧回忆一下,听的时候觉得so 简单,写下来的时候才发现,还无法一次编译通过,这个事情告诉我一个道理,尽可能避免眼高手低!

#include<stdio.h>

int main(void)
{
	char str[] = "bit";
	char* start =str;
	char* end = str;
	while(*end != '\0')
	{
		end ++;		
	}
	int len = end - start;
	printf("length = %d\n",len);
	return 0;
}

gcc 编译运行结果:

length = 3

再来修改一下,

#include<stdio.h>

int my_strlen(char *str)
{	
	char* start =str;
	char* end = str;
	while(*end != '\0')
	{
		end ++;		
	}
	return end - start;
}
int main(void)
{
	char str[] = "bit";
	int len = my_strlen(str);
	printf("length = %d\n",len);
	return 0;
}

gcc 编译运行结果:

length = 3