我有一段代码可以生成随机字符。问题是,每隔一段时间,它就会返回一个错误:
“startIndex不能大于字符串的长度。
参数名称: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”,希望以某种方式,这将为我处理错误。但遗憾的是,它没有做到这一点。或者我使用错误的方式或错误的情况?
任何帮助?
谢谢!
答案 0 :(得分:2)
此代码:
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)
答案 1 :(得分:0)
试试这种方式。我认为它更清洁,更容易理解。 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