博客
关于我
2020-12-03本题要求实现函数,可以根据下表查找到星期,返回对应的序号。
阅读量:633 次
发布时间:2019-03-14

本文共 850 字,大约阅读时间需要 2 分钟。

为了实现该函数,我们可以创建一个包含所有星期几的数组,然后用循环来查找输入字符串是否存在于数组中。如果存在,返回对应的序号;如果不存在或输入无效,则返回-1。

步骤说明:

  • 检查输入字符串的有效性:首先,确保输入字符串不为空。如果输入字符串为空,直接返回-1。
  • 创建星期数组:将所有可能的星期几存储在一个数组中,按照序号从0到6排列。
  • 循环比较:遍历数组中的每一个星期几,使用strcmp函数进行字符串比较。如果找到匹配项,返回当前星期的序号。
  • 返回结果:如果循环结束后没有找到匹配项,返回-1。
  • 代码实现:

    int getindex(char *s) {    if (s == NULL || strlen(s) == 0) {        return -1;    }    static const char *weekays[] = {        "Sunday", "Monday", "Tuesday", "Wednesday",        "Thursday", "Friday", "Saturday"    };    int index = -1;    for (int i = 0; i < 7; i++) {        if (strcmp(s, weekays[i]) == 0) {            index = i;            break;        }    }    return index;}

    解释:

    • 输入检查:首先检查输入字符串s是否为空或NULL,如果是,返回-1。
    • 数组定义:定义了一个静态数组weekays,包含所有有效的星期几字符串。
    • 循环比较:从数组的第一个元素开始,逐一比较输入字符串s是否与当前元素匹配。如果匹配,记录当前索引i并跳出循环。
    • 返回结果:如果在循环中找到匹配项,返回对应的索引;否则,返回-1。

    这个实现高效且直接,确保每个输入字符串只需进行一次循环比较,时间复杂度为O(7),即常数时间。

    转载地址:http://ddooz.baihongyu.com/

    你可能感兴趣的文章
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>