Cardinal To Ordinal Convert - CSharp Language Basics

CSharp examples for Language Basics:Data Type

Description

Cardinal To Ordinal Convert

Demo Code

using static System.Console;
class Program//from w  w w.  jav  a2s  .c  o m
{
   static string CardinalToOrdinal(int number)
   {
      switch (number)
      {
         case 11:
         case 12:
         case 13:
         return $"{number}th";
         default:
         string numberAsText = number.ToString();
         char lastDigit =
         numberAsText[numberAsText.Length - 1];
         string suffix = string.Empty;
         switch (lastDigit)
         {
            case '1':
            suffix = "st";
            break;
            case '2':
            suffix = "nd";
            break;
            case '3':
            suffix = "rd";
            break;
            default:
            suffix = "th";
            break;
         }
         return $"{number}{suffix}";
      }
   }
   static void Main()
   {
      for (int number = 1; number <= 40; number++)
      {
         Write($"{CardinalToOrdinal(number)} ");
      }
   }
}

Result


Related Tutorials