I’m new to VB and I was having some issues with the following code.
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.dllAdditional information: Index and Length must refer to a location
within the string “
I think the error is occurring due to (20, length)). 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.
That’s the point. In your second WriteLine you ask to print the
randomstring starting from the 20th character (starting index ok, there are 21 characters) but then it ask to print for 21 chars (length = 21).Yes, startindex + length = 41 and it is out of the string limits
you could try to fix that line with
or introduce a while loop that prints 20 characters at time