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

    你可能感兴趣的文章
    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'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>