2013-01-13 172 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