unity-game-engineunityscript

How to change a string into integer?


I need to convert a string into an integer.

var floorname = coll.collider.gameObject.name;   //output:block25

var cur = floorname.Substring(5);    //output: 25

var cu = parseInt(cur);

I have a variable floorname which contains the value 'block25' obtained from coll.collider.gameObject.name. Then, I extract the substring '25' using floorname.Substring(5). After that, I parse this substring into an integer using parseInt(cur). When I print cu, it displays the correct value, but I receive the error message

FormatException: Input string was not in the correct format System.Int32.Parse (System.String s).

How can I resolve this issue?


Solution

  • Microsoft's documentation says whitespace is okay in the integer string, but I'm not sure if that includes newline.

    http://msdn.microsoft.com/en-us/library/f56zcx39(v=vs.90).aspx

    It's safest to use String.Trim() before parsing the integer.

    cur = cur.Trim();