如何解析索引和长度必须引用字符串中的位置。参数名称:长度“?

时间:2014-10-16 12:13:48

标签: vb.net string substring

Dim amountorhour As String = "A4"

If amountorhour.Substring(0, 1) = "A" Then
    amount = amountorhour.Substring(1, amountorhour.Length)--**error comes here**
    HrsWorked = 0
Else
    HrsWorked = amountorhour.Substring(1, amountorhour.Length - 1)
    amount = 0

我知道当我要求超出范围的字符串长度时会出现此错误,但在这种情况下,我看不到类似的内容。请帮我解决问题

1 个答案:

答案 0 :(得分:2)

第二个参数是您指定的索引的子字符串的长度。因此传递amountorhour.Length只有在传递0作为第一个返回原始字符串的参数时才有效。

您似乎想要使用除第一个字符之外的所有字符,您可以将the overload与一个参数一起使用:

amount = amountorhour.Substring(1) 

这与

相同
amount = amountorhour.Substring(1, amountorhour.Length - 1) 

顺便说一下,你可以使用

If amountorhour.StartsWith("A") Then

而不是

If amountorhour.Substring(0, 1) = "A" Then