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];
}
次の関数は 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#のものではありません)。
要約: まだ方法がないように見えますが、要件が限られているため、投稿されたような単純な関数を使用できます。