You need to enable JavaScript to run this app. C# Int32.Parse提取字符串数字时+分隔正常x/分隔报错原因问询
优惠活动
大模型
产品
解决方案
定价
更多

C# Int32.Parse提取字符串数字时+分隔正常x/分隔报错原因问询

问题原因解析
  • Int32.Parse()方法支持解析以正负号+/-开头的数字字符串,但不支持以x、/等非数字、非正负号的字符开头的字符串
  • 当你使用+作为分隔符时,input2.Substring(input2.LastIndexOf(@"+"))得到的结果是"+55",符合Int32.Parse()的格式要求,因此可以正常转换
  • 当你使用x、/作为分隔符时,对应Substring得到的结果是"x55"、"/55",开头的分隔符不属于合法的整数字符,因此抛出Input string was not in the correct format异常
修复方案

只要在截取第二个数字的时候,跳过分隔符本身即可,也就是将截取的起始下标加1,该方案适配所有分隔符场景:

// 以x为分隔符的场景示例
string input = "22x55";
int splitIndex = input.LastIndexOf(@"x");
int firstnum = Int32.Parse(input.Substring(0, splitIndex));
// 起始下标+1,跳过分隔符
int secondnum = Int32.Parse(input.Substring(splitIndex + 1));

内容的提问来源于stack exchange,提问作者user12847070

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 06:15:03