2013-01-13 186 views
0

我是VB新手,遇到以下代码出现问题。Visual Basic .substring错误

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个字符。

回答

1

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

这就是要点。在你的第二个WriteLine中,你要求打印从第20个字符开始的random字符串(开始索引ok,有21个字符),但它要求打印21个字符(长度= 21)。
是,则startIndex +长度= 41,这是出字符串限制

你可以尝试修复线与

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

或引入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 
+0

嘿史蒂夫,谢谢你给我看while循环,这实际上解决了我所有的问题,用最少的代码。 我能够解决我的初始错误.. Console.WriteLine(random.Substring(20,length - 20)) 感谢您的帮助! B – Bryce