我正在尝试在C#中进行解析int,但是我在int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C")));行中遇到了异常,如下所示


  “ System.FormatException:输入字符串的格式不正确。


代码如下:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
 class Program
   {
    static void Main()
     {
       string fromTo= "M5000C001";
       int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C")));
       int cFrom = int.Parse(fromTo.Substring(fromTo.LastIndexOf("C") + 1));
       Console.WriteLine("FromTo" + mFrom);
     }
}

最佳答案

尝试这个:

IndexOf将返回您请求的字符文字的索引。

string fromTo= "M5000C001";
int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C") - 1));
int cFrom = int.Parse(fromTo.Substring(fromTo.LastIndexOf("C") + 1));
Console.WriteLine("FromTo" + mFrom);

10-08 16:06