4

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

它只需要处理数字 1 到 31(不需要错误检查)和英语。

4

4 回答 4

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];
}
于 2008-10-03T04:58:56.880 回答
6

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

您会注意到,尽管已注释掉,但我有边界检查。如果传入一个意外值的可能性很小,您可能需要取消注释这些行。

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

于 2008-10-03T04:43:17.977 回答
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。

于 2008-10-03T06:18:05.677 回答
1

在这里查看我的问题:如何将基数转换为序数(它不是 C# 的)。

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

于 2008-10-03T10:19:08.540 回答