-3

I have a problem which I do not understand. Here is my code:

String input = "3 days ago"
String firstCharacter = input[0].ToString(); //Returns 3
int firstCharacter = (int)input[0];  //Returns 51

Why does it return 51?

PS: My code comes from this thread: C#: how to get first char of a string?

More information:

In case that input = "5 days ago", then int firstCharacter is 53.
Community
  • 1
  • 1
Happy Bird
  • 1,012
  • 2
  • 11
  • 29

2 Answers2

5

Casting a char to int in this way will give you its ASCII value which for 3 is equal to 51. You can find a full list here:

http://www.ascii-code.com/

You want to do something like this instead:

Char.GetNumericValue(input[0]);
duncan
  • 1,161
  • 8
  • 14
1

You can also use substring to extract it as a string instead of a char and avoid having to cast it:

        string input = "3 days ago";
        string sFirstCharacter = input.Substring(0, 1);   
        int nFirstCharacter = int.Parse(input.Substring(0, 1));
Innat3
  • 3,561
  • 2
  • 11
  • 29