关于vb.net:Visual Basic .substring错误

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.dll

Additional information: Index and Length must refer to a location
within the string"

我认为由于(20length))导致发生错误。我尝试将长度分配给变量,因此除非尝试使用特定数量的字符,否则程序不会崩溃。

我正在尝试使用任何给定长度的变量,如果该变量大于20个字符,则每行仅打印20个字符。


Additional information: Index and Length must refer to a location
within the string

这就是重点。在第二个WriteLine中,您要求打印从第20个字符开始的random字符串(起始索引正常,有21个字符),但随后要求打印21个字符(长度= 21)。
是的,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