vb.net 如何解析索引和长度必须引用字符串中的某个位置。参数名称:长度”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26404129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resolve Index and length must refer to a location within the string. Parameter name:length"?
提问by user8811
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
I know this error shows up when I am asking for length of string which is out of range but in this scenario, I don't see anything like that. Please help me in figuring out the problem
我知道当我要求超出范围的字符串长度时会出现此错误,但在这种情况下,我没有看到类似的内容。请帮我找出问题所在
回答by Tim Schmelter
The second parameter is the length of the substring from the index that you have specified. So passing amountorhour.Lengthworks only if you pass 0 as first parameter which would return the original string.
第二个参数是您指定的索引中子字符串的长度。因此,amountorhour.Length仅当您将 0 作为第一个参数传递时传递才有效,该参数将返回原始字符串。
It seems that you want to take all but the first character, you can use the overloadwith one parameter:
似乎您想要获取除第一个字符之外的所有字符,您可以使用带有一个参数的重载:
amount = amountorhour.Substring(1)
This is the same as
这与
amount = amountorhour.Substring(1, amountorhour.Length - 1)
As an aside, you can use
顺便说一句,你可以使用
If amountorhour.StartsWith("A") Then
instead of
代替
If amountorhour.Substring(0, 1) = "A" Then

