如何为每月的几天提供后缀?

时间:2008-10-03 04:43:07

标签: c date

在“th”中显示“Wednesday June 5th, 2008”等文字时,我需要一个函数来返回后缀数天。

只需要工作数字1到31(无需错误检查)和英语。

4 个答案:

答案 0 :(得分:9)

这是一个替代方案,它也适用于更大的数字:

static const char *daySuffixLookup[] = { "th","st","nd","rd","th",
                           "th","th","th","th","th" };

const char *daySuffix(int n)
{
    if(n % 100 >= 11 && n % 100 <= 13)
        return "th";

    return daySuffixLookup[n % 10];
}

答案 1 :(得分:5)

以下功能适用于C:

char *makeDaySuffix (unsigned int day) {
    //if ((day < 1) || (day > 31)) return "";
    switch (day) {
        case 1: case 21: case 31: return "st";
        case 2: case 22:          return "nd";
        case 3: case 23:          return "rd";
    }
    return "th";
}

根据要求,它仅适用于1到31的数字。如果您想要(可能,但不一定)原始速度,您可以尝试:

char *makeDaySuffix (unsigned int day) {
    static const char * const suffix[] = {
        "st","nd","rd","th","th","th","th","th","th","th",
        "th","th","th","th","th","th","th","th","th","th"
        "st","nd","rd","th","th","th","th","th","th","th"
        "st"
    };
    //if ((day < 1) || (day > 31)) return "";
    return suffix[day-1];
}

你会注意到我已经注定要在那里办理登记手续了。如果甚至 slightest 可能会传递意外值,您可能想要取消注释这些行。

请记住,对于今天的编译器,对高级语言中更快的内容的天真假设可能不正确:测量,不要猜测。

答案 2 :(得分:2)

const char *getDaySuffix(int day) {
    if (day%100 > 10 && day%100 < 14)
        return "th";
    switch (day%10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    };
}

这个适用于任何数字,而不仅仅是1-31。

答案 3 :(得分:1)

在这里查看我的问题:How to convert Cardinal numbers into Ordinal ones(这不是C#)。

总结:看起来还没有办法,只要您使用有限的要求,就可以使用像发布的那样简单的功能。