2

the following code converts characters A-Z to a number between 1 and 26, all are upper case for simplicity.

    static void Main(string[] args)
    {

        string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        foreach (char c in letters)
        {
            Console.WriteLine(c +" = " + CharToNumber(c));
            Console.ReadLine();
        }
    }

    static int CharToNumber(char character)
    {
        // index starts at 0, 65 is the ascii code for A hence the program -64 so start at 1 therefore A=1
         return (int)Char.ToUpper(character) - 64;
    }

    static char NumberToChar(int number)
    {
        //  code here
    }
}

}

I am trying to do the same but vice versa, so convert that number back to the same character. I am unsure on where to start. Any idea much appreciated, thank you

peter.k
  • 73
  • 2
  • 8

2 Answers2

4

The implementation is just

static char NumberToChar(int number)
{
    return (char) ('A' + number - 1); // "- 1" : You want to start from 1
}

Correspondingly

static int CharToNumber(char character) 
{
    return character - 'A' + 1; // " + 1" : You want to start from 1
}

Note, that in C# char is in fact a 16-bit integer so you can just convert it.

Edit: according to your prior code you also want to modify the Main(string[] args):

  static void Main(string[] args) {
     ...
     // Reverse 
     for (int i = 1; i <= 26; ++i)
       Console.WriteLine(i + " = " + NumberChar(i));
       Console.ReadLine();
     } 
   }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You can cast directly from an integer to a character, which returns the character with the corresponding Unicode value. The Unicode value for A is 65, and the rest of the English alphabet continues in order, so you could just add 64 to your number and return the Unicode character. There are a number of ways to do that.

If you don't want to hard-code the Unicode offset you can do this trick:

static char NumberToChar(int number)
{
    int offset = (int)'A' - 1;
    return (char)(number + offset);
}
Community
  • 1
  • 1
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • thanks a lot for the help, could you tell me what I would put in the 'main' for that to take effect/display? – peter.k May 20 '15 at 15:44