模拟实现strlen函数

对于srelen函数我们要明白一点,它获取的是字符串的首元素地址,即从第一个元素开始查找,知道遇到‘\0’,才会停止。这就要求我们模拟实现时用指针来接收地址。

下面上代码

#include<stdio.h>
#include<string.h>
#include<assert.h>
my_strlen(const char*p)
{
	assert(p != NULL);
	int count = 0;
	while (*p != '\0')
	{
		count++;
		*p++;
	}
	printf("%d", count);
}
int main()
{
	char arr[] = "abcdef";
	my_strlen(arr);
	system("pause");
	return 0;
}

在这段代码中,值得注意有两点:1.是我们需要用断言来进行指针变量是否为空的判断。

                                                   2.是我们需要用const来避免发生对指针所指向内容的修改


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用递归来模拟实现strlen函数。以下是一个示例代码: #include <stdio.h> #include <stdlib.h> #include <assert.h> size_t my_strlen(const char *str) { assert(str != NULL); 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); system("pause"); return 0; } 在这个代码中,我们定义了一个my_strlen函数,它接受一个指向字符数组的指针作为参数。通过递归调用,如果当前字符不是字符串的结束符'\0',则返回1加上调用my_strlen函数传入的下一个字符的指针。最终,当遇到字符串的结束符时,返回0,表示字符串的长度为0。在main函数中,我们调用my_strlen函数来计算字符数组的长度,并将结果打印出来。 这是一个使用递归实现strlen函数的例子。注意,在实际的编程中,我们应该使用标准库中的strlen函数来计算字符串的长度,因为它已经经过充分测试和优化,具有更好的性能和可靠性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [strlen模拟(递归实现)](https://blog.csdn.net/qq_58330935/article/details/127184319)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [C语言:模拟实现strlen的三种方法(非递归,递归,指针)](https://blog.csdn.net/ETalien_/article/details/81263135)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值