博客
关于我
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/

    你可能感兴趣的文章
    NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
    查看>>
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>