【发布时间】:2016-10-15 07:32:36
【问题描述】:
您好,我正在尝试将字符串转换为整数。
下面的代码显示了我尝试将字符串转换为整数的部分。
if (other.gameObject.CompareTag("PickUp"))
{
if ( checkpointboolean == false)
{
string pickupName = other.ToString(); //other = Pickup4
//Remove first 6 letters thus remaining with '4'
string y = pickupName.Substring(6);
print(y); // 4 is being printed
int x = 0;
int.TryParse(y, out x);
print (x); // 0 is being printed
我也尝试了下面的代码,而不是 '0' 我得到了以下错误:
if (other.gameObject.CompareTag("PickUp"))
{
if ( checkpointboolean == false)
{
//Get Object name ex: Pickup4
string pickupName = other.ToString();
//Remove first 6 letters thus remaining with '4'
string y = pickupName.Substring(6);
print(y);
int x = int.Parse(y);
FormatException:输入字符串的格式不正确 System.Int32.Parse(System.String)
【问题讨论】:
-
你有多确定在 4之后没有字符?尝试打印
y.Length... -
你必须用断点一步步调试它
-
这似乎告诉您您的字符串包含无效字符。您确定该子字符串中只有 4 吗?如果您有一个调试器尝试查看该值,错过它然后更改使用 print("[" + y + "]");查看是否还有其他字符
-
尝试修剪 y 以防有多余的间距。 ` int.TryParse(y.Trim(), out x);`
-
@Peter4499:
Trim()在上下文中没有用,因为默认 NumberStyles.Integer == NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign;见msdn.microsoft.com/en-us/library/…