如何为每月的几天提供后缀?
我需要一个函数来在“ Wednesday June 5th, 2008
”中显示像“ th
”这样的文本时返回几天的后缀。
它只需要工作数字1到31(不需要错误检查)和英语。
这是一个替代方案,它也适用于更大的数字:
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]; }
以下function适用于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]; }
你会注意到我已经注定要在那里办理登记了。 如果传递意外值的可能性最小 ,您可能希望取消注释这些行。
请记住,对于今天的编译器,关于高级语言中哪些更快的天真假设可能不正确: 测量,不要猜测。
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。
请参阅我的问题: 如何将基数转换为有序数 (不是C#)。
总结:看起来还没有办法,只要你有限的要求就可以使用像发布的那样简单的function。