您的位置:首页 > 其它

递归和非递归(创建变量)实现strlen

2017-08-09 09:57 260 查看
第一种,使用递归(不创建变量)

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int my_strlen(const char *str)
{
if (*str == '\0')
return 0;
else
return 1 +my_strlen(str + 1);
}
int main()
{
char str[20] = { 0 };
printf("str:");
scanf("%s", &str);
int len = my_strlen(str);
printf("%d\n", len);
system("pause");
return 0;

}


第二种,创建变量

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
#include <assert.h>
int my_strlen(const char*str)
{
int count = 0;
if (*str == NULL)
{
return count = 0;
}
else
{
while (*str++)
{
count++;
}
/*while (*str)
{
count++;
str++;
}也可以使用这种方式实现while循环*/
return count;
}
}
int main()
{
char str[20] = { 0 };
printf("str:");
scanf("%s", &str);
int count = my_strlen(str);
printf("%d\n", count);
system("pause");
return 0;
}


此篇不是很全面,可以查看下一篇:用三种方法模拟实现strlen函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐