设为首页 加入收藏

TOP

[C语言] 实现strlen
2015-11-19 23:07:12 来源: 作者: 【 】 浏览:13
Tags:语言 实现 strlen
#include 
#include 
 
//方法一:使用指针
 
int my_strlen(const  char *str)
{
    assert(str);
    int count = 0;
    while (*str++)
    {
        count++;
    }
    return count;
}
 
int main()
{
    char *str = "abcdef";
    int len = my_strlen(str);
    printf("%d\n", len);
    system("pause");
    return 0;
}
 
//方法二:递归实现
 
int my_strlen(const char *str)
{
    if (*str =='\0' )
    {
        return 0;
    }
    else
    {
        return 1 + my_strlen(str+1);  //str+1
    }
}
 
int main()
{
    char *str = "abcdef";
    //strlen(str) == 1+strlen(str+1)==1+1+strlen(str+1+1)
    int len = my_strlen(str);
    printf("%d\n", len);
    system("pause");
    return 0;
}

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[C语言] 实现strstr函数 下一篇[注意]C 运算符优先级 口诀 易错点

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: