不使用任何辅助变量实现strlen(递归实现strlen)

本文详细探讨了通过自定义函数计算字符串长度的方法,并对比了不同实现方式下的执行时间和函数长度之间的关系,揭示了优化代码效率的潜在策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/******************************************************
不允许调用库函数,也不允许使用任何全局或局部变量编写 int strlen(char *strDest)
******************************************************/
#include<iostream>
#include<time.h>
#include<cstring>
using namespace std;
int mystrlen(char *str)
{
    return *(str++) ? mystrlen(str) + 1 : 0;
}

int main()
{
    char a[] =
    "If you don't take the time to attract a woman first,\
     you won't give her a reason to want to even have a conversation with you.";
    unsigned long start,stop;
    start=time(NULL); //取值为秒
    cout<<a<<endl;
    stop=time(NULL);
    cout<<"running time : "<<stop-start<<endl;
    start=time(NULL); //取值为秒
    cout<<"mystrlen(a)= "<<mystrlen(a)<<endl;
    stop=time(NULL);
    cout<<"running time : "<<stop-start<<endl;
    cout<<"strlen(a)= "<<strlen(a)<<endl;
}
/******************
If you don't take the time to attract a woman first,     you won't give her a re
ason to want to even have a conversation with you.
running time : 0
mystrlen(a)= 130
running time : 0
strlen(a)= 130

Process returned 0 (0x0)   execution time : 0.919 s
Press any key to continue.

********************


### 使用数组模拟实现C语言的`strlen`函数 在C语言中,`strlen`函数的功能是计算字符串的长度,其计算依据是字符串末尾的终止符`\0`。字符串长度等于从字符串的起始位置到`\0`之间的字符数(包括`\0`本身)[^4]。为了模拟实现`strlen`函数的功能,可以通过数组的方式实现,而无需依赖标准库函数。 #### 方法一:使用计数器遍历数组 可以通过遍历数组元素,逐个检查字符是否为`\0`,直到找到字符串的结束符为止。在此过程中,每遍历一个字符就增加计数器的值。 ```c #include <stdio.h> int my_strlen(char arr[]) { int count = 0; while (arr[count] != '\0') { count++; } return count; } int main() { char arr[] = "Hello, World!"; int length = my_strlen(arr); printf("Length of the string: %d\n", length); return 0; } ``` 在上述代码中,`my_strlen`函数接收一个字符数组`arr[]`,通过逐个访问数组中的每个字符,直到遇到`\0`为止,从而计算出字符串的长度。 #### 方法二:递归实现 还可以通过递归的方法实现字符串长度的计算。递归的核心思想是将问题分解为更小的子问题,直到达到基本情况为止。 ```c #include <stdio.h> int my_strlen(char arr[]) { if (arr[0] != '\0') { return 1 + my_strlen(arr + 1); } else { return 0; } } int main() { char arr[] = "Hello, World!"; int length = my_strlen(arr); printf("Length of the string: %d\n", length); return 0; } ``` 在递归实现中,每次递归调用时,将数组的起始地址向后移动一个字符,并将递归的结果加1。当遇到`\0`时,递归终止,返回0。 #### 方法三:使用循环和索引变量 除了直接使用数组索引遍历外,还可以引入一个额外的变量来跟踪当前的位置,从而实现字符串长度的计算。 ```c #include <stdio.h> int my_strlen(char arr[]) { int i = 0; while (arr[i] != '\0') { i++; } return i; } int main() { char arr[] = "Hello, World!"; int length = my_strlen(arr); printf("Length of the string: %d\n", length); return 0; } ``` 这种方法与第一种方法类似,但更直观地展示了如何通过索引变量来计算字符串的长度。 ### 总结 通过上述三种方法,可以有效地使用数组来模拟实现C语言中的`strlen`函数。无论是通过计数器、递归还是索引变量的方式,核心思想都是通过遍历字符串中的字符,直到遇到终止符`\0`为止。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值