金丹二层 —— 字符串长度求解的四种方法

前言:

1.CSDN由于我的排版不怎么好看,我的有道云笔记比较美观,请移步有道云笔记

2.修炼必备

        1)入门必备:VS2019社区版,下载地址:Visual Studio 较旧的下载 - 2019、2017、2015 和以前的版本 (microsoft.com)

        2)趁手武器:印象笔记/有道云笔记

        3)修炼秘籍:牛客网 - 找工作神器|笔试题库|面试经验|实习招聘内推,求职就业一站解决_牛客网 (nowcoder.com)

        4)雷劫必备:leetcode 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 

        注:遇到瓶颈怎么办?百度百科_全球领先的中文百科全书 (baidu.com)

字符串的求解

1.问题描述

给定一个字符串(长度在0-1000),求出该字符串的长度,注:输入字符串的各字符之间不存在空格

2. 代码解释

        法一:使用库函数strlen()求解【需包含头文件string.h】

注:strlen()函数是用于求字符串长度的,是得到'\0'字符之前的所有字符数

#include <stdio.h>
#include <string.h>

int main()
{
    char str[1000] = "";
    
    while(scanf("%s", str)!=EOF)
        printf("%d\n", strlen(str));
    return 0;
}

EOF是一个宏,它本质是-1,当scanf()函数返回EOF的时候,就说明scanf()没有任何输入。

EOF的宏定义如下:

        #define EOF -1

        法二: 计数器 

思路分析:使用一个计数器变量计算字符串'\0'之前的字符总数

#include <stdio.h>
#include <assert.h>

int getCharTotal(const char* str)
{
    assert(str);//判断空指针
    int count = 0;

    //统计'\0'之前的字符数
    while (*str != '\0')
    {
        count++;//计数
        str++;//指向下一个字符
    }
    return count;
}

int main()
{
    char str[100] = "";
    while (scanf("%s", str) != EOF)
    {
        int total = getCharTotal(str);
        printf("%d\n", total);
    }
    return 0;
}

        法三:指针-指针

思路分析:引入一个字符指针,让该字符指针指向字符串的首地址,使该指针遍历到'\0'的地址后,让指针指向的地址减去字符串起始地址,即得到'\0'之前的字符总数

#include <stdio.h>
#include <assert.h>

int getCharTotal(const char* str)
{
    assert(str);//判断空指针
    const char* cur = str;//遍历指针
    
    //使遍历指针遍历到'\0'的位置
    while (*cur != '\0')
    {
        cur++;
    }
    //指针-指针得到的是字符个数
    return cur - str;
}

int main()
{
    char str[100] = "";
    while (scanf("%s", str) != EOF)
    {
        int total = getCharTotal(str);
        printf("%d\n", total);
    }
    return 0;
}

         法四:递归

思路分析:字符没有遇到'\0'的时候进行递归,进行递归的时候,需要得到当前字符指向它的下一个字符的地址,且字符串长度+1,遇到'\0'之后,返回字符串的长度

#include <stdio.h>
#include <assert.h>

int getCharTotal(const char* str)
{
    assert(str);//判断空指针
    if (*str == '\0')
        return 0;
    return 1 + getCharTotal(str + 1);
}

int main()
{
    char str[100] = "";
    while (scanf("%s", str) != EOF)
    {
        int total = getCharTotal(str);
        printf("%d\n", total);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_63200557/article/details/129592672