1

我有一段代码可以生成随机字符。问题是,每隔一段时间,它就会返回一个错误:
“startIndex cannot be greater than length of string. Parameter name: startIndex”

如何防止发生这种错误?

这是我的代码:

Friend Function gentCtrlChar()
    Dim ran As New Random
    Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim alpha2 As String = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
    Dim rdm As New Random
    Dim genChar As String = ""
    For i As Integer = 1 To 52
        Dim selChar As Integer = rdm.Next(1, 28)
        Dim selChar2 As Integer = rdm.Next(1, 28)
        genChar = genChar + "" + alpha.Substring(selChar, 1) + "" + alpha2.Substring(selChar2, 1)
        On Error Resume Next
        Exit For
    Next
    Return genChar
End Function

如您所见,我尝试放置“On Error Resume Next”,希望以某种方式为我解决错误。但可悲的是,它没有做它的工作。还是我以错误的方式或错误的情况使用它?

有什么帮助吗?

谢谢!

4

2 回答 2

3

这段代码:

Dim selChar As Integer = rdm.Next(1, 28)

有时会返回一个比这个字符串的长度长(27 或 28)的数字:

Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"  (only 26 characters long)

因此,当 selChar 为 26 或更大时,这是无效的。

alpha.Substring(selChar, 1)

最简单的解决方法是:

Dim selChar As Integer = rdm.Next(0, alpha.Length) 
Dim selChar2 As Integer = rdm.Next(0, alpha2.Length) 
于 2013-09-17T20:29:22.507 回答
1

试试这个方法。我认为它更干净,易于理解。A - Z 与 ascii 映射上的 65 - 90 相同,因此很容易将整数转换为 Char 值。然后我们只使用字符串生成器来使其更易于阅读。

Dim rdm As New Random
Dim genChar As New StringBuilder()
For i As Integer = 1 To 52
    Dim selChar As Char = Chr(rdm.Next(65, 90))
    Dim selChar2 As Char = Chr(rdm.Next(65, 90))
    genChar.Append(selChar)
    genChar.Append(selChar2)
Next
Return genChar.ToString
于 2013-09-17T21:39:55.907 回答