strlen的模拟实现

目录

1.计数器

2.递归

3.指针-指针


1.计数器

#define _crt_secure_no_warnings
#include <stdio.h>
#include <assert.h>
#pragma warning(disable:4996)

int my_strlen(char const* str)
{
	int count = 0;
    assert(str);   //声明,防止arr传过来空指针,需要包含头文件 #include <assert.h>
	while (*str != '\0')
	{
		count++;
		str++;
	}
	return count;
}

int main()
{
	char arr[] = "abcdef";
	int len = my_strlen(arr);
	printf("%d\n", len);
	return 0;
}

2.递归

  递归的特点是:它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解。

  递归的主要思考方式在于:把大事化小

  在模拟实现strlen函数中,若是遇到字符'\0',则返回0,否则,返回1+my_strlen(指针+1),且指针会越来越趋近于’\0‘

#define _crt_secure_no_warnings
#include <stdio.h>
#include <assert.h>
#pragma warning(disable:4996)

int my_strlen(char const* str)
{
    assert(str);   
	if (*str == '\0')
	{
		return 0;
	}
	else
	{
		return 1 + my_strlen(str + 1);
	}

}

int main()
{
	char arr[] = "abcdef";
	int len = my_strlen(arr);
	printf("%d\n", len);
	return 0;
}

3.指针-指针

#define _crt_secure_no_warnings
#include <stdio.h>
#include <assert.h>
#pragma warning(disable:4996)

int my_strlen(char const* str)
{
	char* p = str;
    assert(str);  
 	int i = 0;
	while (*p != '\0')
	{
		p++;
	}
	return p - str;
}

int main()
{
	char arr[] = "abcdef";
	int len = my_strlen(arr);
	printf("%d\n", len);
	return 0;
}

注:指针-指针的绝对值是指针和指针之间元素的个数。指针-指针,计算的前提条件是两个指针指向的是同一块空间。

评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值