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

来源:互联网 发布:公路法律法规题库软件 编辑:程序博客网 时间:2024/06/04 19:16

第一种,使用递归(不创建变量)

#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函数。

原创粉丝点击