我需要一个函数来在显示像" th
"中的" Wednesday June 5th, 2008
" 这样的文本时返回几天的后缀.
它只需要工作数字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];
}
Run Code Online (Sandbox Code Playgroud)
以下功能适用于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";
}
Run Code Online (Sandbox Code Playgroud)
根据要求,它仅适用于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];
}
Run Code Online (Sandbox Code Playgroud)
你会注意到我已经在那里检查,但是已经注释掉了.如果传递意外值的可能性最小,您可能希望取消注释这些行.
请记住,对于今天的编译器,对高级语言中更快的内容的天真假设可能不正确:测量,不要猜测.