-1

In a C# console application I want to convert an int to a string, then check the characters in the new string, and convert them to and int. This is what I have so far to do that:

    int charNum = 0;
    int value = 111
    string valueStr = value.ToString();
    int numVariant = valueStr.ToCharArray()[charNum];

Then I add this to output their values

    Console.WriteLine(numVariant + " " + valueStr + " " + charNum);
    Console.ReadLine();

And strangely it returns

    49 111 0

Whereas what I expected it to return is

  1 111 0

So what I assume is something went wrong with converting the char to a int, any suggestions on how to fix this?

User2935
  • 3
  • 1
  • `int numVariant = valueStr.ToCharArray()[charNum] - '0';` – Dmitry Bychenko Sep 21 '17 at 19:31
  • Possible duplicate of [c# why does this return 49: Convert.ToInt32('1')](https://stackoverflow.com/questions/3665978/c-sharp-why-does-this-return-49-convert-toint321) – Katana Sep 21 '17 at 19:39

2 Answers2

1

Replace int numVariant = valueStr.ToCharArray()[charNum]; with int numVariant = int.Parse(valueStr[charNum].ToString());

Otherwise it takes the ASCII value of 1

ravi kumar
  • 1,548
  • 1
  • 13
  • 47
1

49 is the character of '1's ascii decimal value. It is storing that because you are assigning the value to an int32 and the compiler is automatically casting the value. Simply change:

int numVariant = valueStr.ToCharArray()[charNum];

To:

char numVariant = valueStr.ToCharArray()[charNum];
JSextonn
  • 226
  • 3
  • 13