我正在为我的键盘修改一些驱动程序软件,其中一部分是将日期输出到键盘屏幕的插件。目前它说1月1日,但我真的希望它说第1,第2,第3或第4或其他什么。
我一直在寻找某种代码,这些代码会给我一些关于如何做到这一点的想法,但我只能找到C#的例子而我正在使用C.
编辑:
const char *ordinals[] = {"", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st"};
sprintf(date, "%s %s", ordinals[t->tm_mday], mon);
答案 0 :(得分:8)
由于您只需要数字1
到31
,因此最简单的方法是定义一个序数数组,如下所示:
const char *ordinals[] = {"", "1st", "2nd", "3rd", "4th"..., "31st"};
...
printf("%s of %s", ordinals[dayNumber], monthName);
这比在算法上做得更好,因为如果你以后在某个时候遇到这种情况,它更具可读性,并且更容易国际化。
答案 1 :(得分:5)
这适用于所有非负n
:
char *suffix(int n)
{
switch (n % 100) {
case 11: case 12: case 13: return "th";
default: switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
}
printf("%d%s\n", n, suffix(n));
答案 2 :(得分:1)
你可以用一个条件来做。
#include <stdio.h>
const char *suff;
switch (day)
{
case 1: /* fall-through */
case 21: /* fall-through */
case 31:
suff = "st";
break;
case 2: /* fall-through */
case 22:
suff = "nd";
break;
case 3: /* fall-through */
case 23:
suff = "rd";
break;
default:
suff = "th";
break;
}
printf("%d%s\n", day, suff);
答案 3 :(得分:1)
void day_to_string(int day, char *buffer)
{
char *suff = "th";
switch(day)
{
case 1:
case 21:
case 31:
suff = "st";
break;
case 2:
case 22:
suff = "nd";
break;
case 3:
case 23:
suff = "rd";
break;
}
sprintf(buffer, "%d%s", day, suff);
}
应该这样做。但请注意,如果您希望将程序翻译成其他语言,则可能需要遵循dasblinkenlight的建议,因为您可能会发现某些语言中的规则与英语中的规则不同。