c# - 在 C# 中执行 ParseInt 时输入字符串的格式不正确

标签 c# asp.net .net

我正在尝试在 C# 中执行 Parse int,但在 int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C"))); 行中出现异常像下面一样

"System.FormatException: Input string was not in a correct format.

代码如下:

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 将返回您所请求的字 rune 字的索引。

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);

引用这个documentation .

关于c# - 在 C# 中执行 ParseInt 时输入字符串的格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45348143/

相关文章:

c# - 如何在没有附加类的情况下解析 json?

c# - 事先检查 `System.Activator.CreateInstance(Of T)` 是否会失败

c# - 在接收消息时创建 View

c# - 如何从其访问器中获取属性的唯一标识符

c# - 正则表达式长度验证 : Ignore leading and trailing whitespaces

.net - 如何获得ASP.NET应用程序的最后启动时间?

c# - 由于对象的当前状态,操作无效

c# - 在 MailKit 中,如何获取邮件的原始表示形式?

c# - 哪个 DLL 包含 Microsoft.Powershell.Command 命名空间下的异常?

c# - 如何每天重置应用程序变量