-1

I have this code which gets the index of the '[' in the string. It then creates an integer from the next character in the string which I would assume would be '9' in this example. However value is getting set to 57?

string text = "Red Onyx : Text 1 - [9]";

int index = text.IndexOf("[");
int value = Convert.ToInt16(text[index+1]);

I have tried doing just text[index], text[index -1], and text[index +2]

Ralt
  • 2,084
  • 1
  • 26
  • 38

1 Answers1

4

text[index+1] would return you a character and converting it to Int16 will return its ASCII value which is 57 for 9.

You can use char.GetNumericValue :

int value = (int) char.GetNumericValue(text[index + 1]);

or use the second overload of char.GetNumericValue which takes string and index like:

int value = (int) char.GetNumericValue(text,index + 1);

Or

int value = Convert.ToInt16(text[index + 1] +""); //explicitly make it string "9"
                                                  //or simpler text[index + 1].ToString()

Also there is no need to use Convert.ToInt16 if you are going to store result in Int32 or int

Habib
  • 219,104
  • 29
  • 407
  • 436
  • +1. I was just typing this. You're faster than me. You could also do `Convert.ToInt16(text.SubString(index+1,1))` or `Convert.ToInt16(text[index+1].ToString())` – Nick Nov 17 '14 at 15:55