strlen的模拟

题目内容

递归和非递归分别实现strlen

strlen函数

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

源程序及运行结果

#include <stdio.h>

int strlen(char *a)
{
	if(*a!='\0')
	{
		return 1+strlen(a+1);
	}
}

int nostrlen(char *a)
{
	int count=0;
	
	while(*a!='\0')
	{
		count++;
		a++;
	}

	return count;
}
int main()
{
 	char a[]="hkdiausaod";
 	int count,count1;
 	
 	count1=strlen(a);
 	count=nostrlen(a);
 	printf("递归字符串长度为:%d\n",count1);
 	printf("非递归字符串长度为:%d",count);
 	 
 	return 0;
} 

在这里插入图片描述

  • 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、付费专栏及课程。

余额充值