习题11-2 查找星期 (15 分)

本题要求实现函数,可以根据下表查找到星期,返回对应的序号。

函数接口定义:

int getindex( char *s );

函数getindex应返回字符串s序号。如果传入的参数s不是一个代表星期的字符串,则返回-1。

裁判测试程序样例:

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

#define MAXS 80

int getindex( char *s );

int main()
{
    int n;
    char s[MAXS];

    scanf("%s", s);
    n = getindex(s);
    if ( n==-1 ) printf("wrong input!
");
    else printf("%d
", n);

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例1:

Tuesday

输出样例1:

2 

输入样例2:

today

输出样例2:

wrong input!

提交:

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

#define MAXS 80

int getindex( char *s ){
    char *day[7] = {
        "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
    };
    for (int i=0;i < sizeof(*day)-1;i++) {//sizeof(*day)这里包含结束字符串null所以这里结果为8 //sizeof(day)表示指针为4
//         if (*s == *day[i]) return i;//不可行 Thursday会返回2 Saturday返回0
        if (strcmp(day[i],s) == 0) return i;//strcmp函数是string compare(字符串比较)的缩写,用于比较两个字符串并根据比较结果返回整数。
        //基本形式为strcmp(str1,str2),若str1=str2,则返回零;若str1<str2,则返回负数;若str1>str2,则返回正数
    }
    return -1;
};

int Main()
{
    int n;
    char s[MAXS];

    scanf("%s", s);
    n = getindex(s);
    if ( n==-1 ) printf("wrong input!
");
    else printf("%d
", n);

    return 0;
}

/* 你的代码将被嵌在这里 */
原文地址:https://www.cnblogs.com/cgy-home/p/15039585.html