栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

(C语言)求字符串长度的三种方法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(C语言)求字符串长度的三种方法

目录

调用内置函数strlen求字符串长度

创建临时变量计算字符串长度

不创建临时变量计算字符串长度(递归)


我们知道C语言是自带内置函数strlen求字符串长度的,但其实我们也可以自己编写函数来求字符串长度

调用内置函数strlen求字符串长度
#include 
#include 

int main()
{
    char s[] = "abc";
    int len = strlen(s);
    printf("%d ",len);
    return 0;
}

创建临时变量计算字符串长度

首先,我们自定义函数my_strlen求字符串长度

在my_strlen中用count统计字符的个数,我们传入的char类型的指针str,对他进行解引用(*str)得到str指向的值,循环判断(*str)是否等于‘’,如果不等,则count+1,str指向下一个字符;如果相等,则说明遍历到了字符串结尾,最后返回count,也就是统计的字符的个数。

代码实现如下:

#include 

int my_strlen(char* str)
{
    int count = 0; //计数
    while(*str != '')
    {
        count++;
        str++;
    }
    return count;
}

int main()
{
    char s[] = "abc";
    int len = my_strlen(s);
    printf("%d ",len);
    return 0;
}

不创建临时变量计算字符串长度(递归)

递归的主要思想:大事化小

使用递归的两个必要条件:

1、存在限制条件,当满足这个限制条件的时候,递归便不再继续

2、每次递归调用之后越来越接近这个限制条件


计算字符串(abc)长度的递归思想:

代码实现如下:

#include 

int my_strlen(char* str)
{
    if(*str != '')
    {
        return 1 + my_strlen(str+1);
    }
    else
        return 0;
}

int main()
{
    char s[] = "abc";
    int len = my_strlen(s);
    printf("%d ",len);
    return 0;
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1029655.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号