Visual Basic .substring error
我是VB的新手,以下代码存在一些问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Dim random As String ="asfdgasfdgasfdgasfd11" Dim length As Integer = Nothing length = random.Length Console.WriteLine(random.Length) Console.WriteLine(length) Console.WriteLine() Console.WriteLine() Console.ReadLine() If length <= 20 Then Console.WriteLine(random.Substring(0, length)) ElseIf length <= 40 Then Console.WriteLine(random.Substring(0, 20)) Console.WriteLine(random.Substring(20, length)) End If Console.ReadLine() |
错误:
" An unhandled exception of type 'System.ArgumentOutOfRangeException'
occurred in mscorlib.dllAdditional information: Index and Length must refer to a location
within the string"
我认为由于(
我正在尝试使用任何给定长度的变量,如果该变量大于20个字符,则每行仅打印20个字符。
Additional information: Index and Length must refer to a location
within the string
这就是重点。在第二个WriteLine中,您要求打印从第20个字符开始的
是的,startindex长度= 41,并且超出了字符串限制
您可以尝试使用
修复该行
1 | Console.WriteLine(random.Substring(20, length - 20)) |
或引入一个while循环,该循环一次输出20个字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | length = random.Length Console.WriteLine(random.Length) Console.WriteLine(length) Console.WriteLine() Console.WriteLine() Console.ReadLine() Dim curStart = 0 Dim loopCounter = 0 while(curStart < random.Length) Console.WriteLine(random.Substring(curStart, System.Math.Min(20, length - 20 * loopCounter))) curStart = curStart + 20 loopCounter = loopCounter + 1 End While |