当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何为每月的几天提供后缀?》经验,为你挑选了2个好方法。

我需要一个函数来在显示像" th"中的" Wednesday June 5th, 2008" 这样的文本时返回几天的后缀.

它只需要工作数字1到31(不需要错误检查)和英语.



1> Adam Pierce..:

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

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];
}



2> paxdiablo..:

以下功能适用于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];
}

你会注意到我已经在那里检查,但是已经注释掉了.如果传递意外值的可能性最小,您可能希望取消注释这些行.

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

推荐阅读
Chloemw
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有