我在代码中发现了一个错误,其中子字符串不起作用,它说“startIndex不能大于字符串的长度”
static int MyIntegerParse(string possibleInt)
{
int i;
return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;
}
我在这里使用了这个程序:
var parsed = File.ReadLines(filename)
.Select(line => line.Split(' ')
.Select(MyIntegerParse)
.ToArray())
.ToArray();
但是我不明白为什么会出现错误,因为我之前已经使用了子字符串并且它正常工作,我可以在这里寻求帮助吗? thnaks。
示例字符串:
10192 20351 30473 40499 50449 60234
10192 20207 30206 40203 50205 60226
10192 20252 30312 40376 50334 60252
答案 0 :(得分:1)
Substring
包含少于两个字符时, possibleInt
将失败,因此您也应该将该测试添加到代码中。我怀疑你Split
调用在某些情况下产生一个空字符串。这个空字符串被传递到你的int-parser,然后在Substring
调用失败。所以,你应该做两件事:
摆脱空字符串非常简单:
var parsed = File.ReadLines(filename)
.Select(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(MyIntegerParse)
.ToArray())
.ToArray();
添加对空字符串的有意处理可以这样做:
static int MyIntegerParse(string possibleInt)
{
if (string.IsNullOrEmpty(possibleInt) || possibleInt.Length < 2)
{
return 0;
}
int i;
return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;
}
...或者如果你是紧凑和难以阅读的结构的粉丝:
static int MyIntegerParse(string possibleInt)
{
int i;
return (!string.IsNullOrEmpty(possibleInt)
&& possibleInt.Length >= 2
&& int.TryParse(possibleInt.Substring(2), out i)) ? i : 0;
}
不,当我收到太短的字符串时,我选择返回0
。在您的情况下,返回其他值,抛出异常或使用Debug.Assert
语句可能更有意义。
答案 1 :(得分:0)
possibleInt
字符串长度必须至少为两个字符。如果不是,那么你会看到你所描述的错误。
答案 2 :(得分:0)
在你的return语句之前添加它,看看是否有助于你弄清楚发生了什么:
Debug.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);
在调试模式下运行时,如果不满足上述两种情况,则会抛出异常。
你也可以使用这样的Code Contract:
Contract.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);
答案 3 :(得分:0)
您尝试解析的行不是那么长。来自Substring的C#规范:
The zero-based starting character position of a substring in this instance.
您传入的字符串中包含0或1个字符。您需要修改代码以处理这种情况。
编辑:此外,您应该使用split的重载删除文件中的空元素:
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntires)
答案 4 :(得分:0)
您正在获取此异常,因为您正在尝试从索引开始获取字符串的子字符串,该索引大于字符串的长度。
someString.Substring(x)
将从字符串中的位置x开始为您提供someString
的子字符串,并且它基于零。您将收到此异常,因为在这种情况下,2超出了特定字符串长度的范围。
坚持尝试捕获它或断点,你会看到导致此异常的字符串的长度小于3。