我尝试从字符串1,2,3
中引出Data:[1,2,3]
作为字符串。使用以下代码执行此操作,使我Error Index and length must refer to a location within the string
似乎完全瞎了,但我看不出有什么问题。有人可以帮我吗?
Sub Main()
Dim name As String = "Data:[1,2,3]"
Console.Write(name.Substring(6, name.Length - 1))
Console.Read()
End Sub
答案 0 :(得分:3)
String.Substring
中的第二个参数是长度,因此应该从第一个参数的索引中获取的字符数。您应该改用括号:
Dim startIndex = name.IndexOf("["c)
If startIndex >= 0 Then
Dim endIndex = name.IndexOf("]"c, startIndex)
If endIndex >= 0 Then
startIndex += 1 ' because you dont want to include the brackets
Dim data = name.Substring(startIndex, endIndex - startIndex)
End If
End If