简体   繁体   English

Visual Basic .substring错误

[英]Visual Basic .substring error

I'm new to VB and I was having some issues with the following code. 我是VB的新手,但是以下代码存在一些问题。

    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()

Error: 错误:

" An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll “ mscorlib.dll中发生类型'System.ArgumentOutOfRangeException'的未处理异常

Additional information: Index and Length must refer to a location within the string " 附加信息:索引和长度必须引用字符串“

I think the error is occurring due to ( 20 , length )). 我认为错误是由于( 20length ))而发生的。 I tried to assign length to a variable so the program does not crash unless the trying is a specific number of characters. 我尝试将长度分配给变量,因此除非尝试使用特定数量的字符,否则程序不会崩溃。

I am attempting to have a variable of any given length and if it is greater than 20 characters then only print 20 characters per line. 我正在尝试使用任何给定长度的变量,如果该变量大于20个字符,则每行仅打印20个字符。

Additional information: Index and Length must refer to a location within the string 附加信息:索引和长度必须引用字符串中的位置

That's the point. 这才是重点。 In your second WriteLine you ask to print the random string starting from the 20th character (starting index ok, there are 21 characters) but then it ask to print for 21 chars (length = 21). 在第二个WriteLine中,您要求打印从第20个字符开始的random字符串(起始索引正常,有21个字符),但随后要求打印21个字符(长度= 21)。
Yes, startindex + length = 41 and it is out of the string limits 是的,startindex + length = 41,它超出了字符串限制

you could try to fix that line with 你可以尝试用

Console.WriteLine(random.Substring(20, length - 20))

or introduce a while loop that prints 20 characters at time 或引入一个while循环,一次打印20个字符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM