-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. 
3
  • 6
    Because the 3 is a char with 51 code. You cast a char to an int. Check asciitable.com Commented Oct 12, 2016 at 15:33
  • What are you trying to achieve? This is normal behavior in .NET. You can cast a char to int and int to char. Commented Oct 12, 2016 at 15:39
  • Maybe int.TryParse is what you're looking for? Commented Oct 12, 2016 at 15:43

2 Answers 2

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]); 
Sign up to request clarification or add additional context in comments.

Comments

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)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.