tags:

views:

525

answers:

5

I need a function to return a suffix for days when displaying text like the "th" in "Wednesday June 5th, 2008".

It only need work for the numbers 1 through 31 (no error checking required) and English.

+4  A: 

The following function works for C:

char *makeDaySuffix (int day) {
    switch (day) {
        case 1: case 21: case 31: return "st";
        case 2: case 22:          return "nd";
        case 3: case 23:          return "rd";
    }
    return "th";
}

As requested, it only works for the numbers 1 through 31 inclusive. If you want (possibly, but not necessarily) raw speed, you could try:

char *makeDaySuffix (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"
    };
    return suffix[day];
}

Just keep in mind that, with the compilers of today, naive assumptions about what is faster in a high-level language may not be correct: measure, don't guess.

paxdiablo
+3  A: 

Please see this question.

Chris Jester-Young
+7  A: 

Here is an alternative which should work for larger numbers too:

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];
}
Adam Pierce
That's a neat solution - care to turn your hand to an internationalised version?
belugabob
P.S. I know that it wasn't part of the original question, but it is an interesting exercise.
belugabob
Ha ha, an international version would be completely different, probably lookup tables would be the best way to implement it.
Adam Pierce
A: 
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";
    };
}

This one works for any number, not just 1-31.

Milan Babuškov
+1  A: 

See my question here: http://stackoverflow.com/questions/135946/i18n-able-way-to-get-number-ordinal-in-cmfc-on-windows-1-1st-2-2nd-etc (it's not the C# one).

Summary: looks like there's no way yet, with your limited requirements you can just use a simple function like the one posted.

Roel