递归和非递归分别实现strlen

1.非递归

#include<stdio.h>
#include<assert.h>
int my_strlen(const char *p)
{
    assert(p != NULL);
    int num = 0;
    while (*p)
    {
        num++;
        p++;
    }
    return num;
}
int main()
{
    char *p = "abcdefg";
    int ret = my_strlen(p);
    printf("%d", ret);
    return 0;
}

2.递归

#include<stdio.h>
#include<assert.h>
int my_strlen(const char *p)
{
    assert(p != NULL);
    if (*p == '\0')
    {
        return 0;
    }
    else
    {
        return 1 + my_strlen(p + 1);
    }
}
int main()
{
    char *p = "abcdefg";
    int ret = my_strlen(p);
    printf("%d\n", ret);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40995778/article/details/80294569
今日推荐