打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C语言--求字符串长度的三种解法

http://9195095.blog.51cto.com/9185095/1706394

2015

问题:

    求一个字符串的三种解法

一、计数的方法


#include<stdio.h>
#include<assert.h>
int my_strlen( char* str)
{
    int count=0;
    while (*str)
    {
        count++;
        str++;
    }
    return count;
}
int main(void)
{
    char *arr = "abcef";
    int ret = my_strlen(arr);
    printf("%d\n", ret);
}

二、指针-指针的方法


#include<stdio.h>
#include<assert.h>
int  my_strlen(const char*str)
{
    assert(srt);
    const char* ret = str;
    while (*ret++)
    {
        ;
    }
    return(ret - str-1);
}
     
int main(void)
{
    char *arr = "abcdef";
     printf("%d\n",my_strlen(arr));   
}

三、用递归的方法


#include<stdio.h>
#include<assert.h>
int my_strlen(char* srt)
{
    assert(srt);
    if (*srt == '\0')
    {
        return 0;
    }
    else
    {    
        srt++;
        return (1 + my_strlen(srt));
         
    }
}
int main(void)
{
    char *arr = "abcdef";
    printf("%d\n", my_strlen(arr));
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
UC头条:字符串函数剖析
微软面试题——反转字符串
一文讲解C语言字符串
strcmp?strcpy?strcat?strlen?的实现?以及与strncat?st...
Sizeof与Strlen的区别与联系
CrackCode 题目整理 (第一章)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服