用C语言模拟实现库函数strlen


模拟实现库函数strlen
★要想模拟实现strlen函数,我们首先要知道strlen函数的作用是什么?它的函数原型是什么?

●strlen函数的作用仅仅是一个计数器的工作,它从内存的某个位置(可以是字符串的开头,中间某个位置,甚至是某个不确定的内存区域)开始计数,直到碰到第一个字符串结束符'\0'为止,然后返回计数器值(长度不包含'\0')。

●下面是在MSDN里strlen函数的原型:

现在,开始模拟实现函数strlen,下边是参考代码:
int my_strlen(const char *str)
{
	int count = 0;
	assert(str != NULL);//断言,指针为空,打印出错误信息
	while (*str++)//遇到'\0'停止,不算'\0'
	{
		count++;
	}
	return count;
}

下面试一个测试文件:
#include<stdio.h>
#include<assert.h>
#include<windows.h>

int main()
{
	int len=0;
	char *p = "abcdef";
	len=my_strlen(p);
	printf("len=%d\n", len);
	system("pause");
	return 0;
}
完整代码移步——> my_strcpy

猜你喜欢

转载自blog.csdn.net/hansionz/article/details/80053859