我正在编写一个简单的加密/解密程序,遇到了一个小问题。正在生成所有字符的不同字符串,以唯一地标识它们。这些字符串本来应该是相同的长度,但似乎不是。有问题的代码:(可以查看here的完整代码)
Dim genLength As Integer = 0
Dim charNow As Integer = 0
Dim charGenned As String
Dim rndGend As Integer = 0
While genLength < enhancedMode
fs.Write(arrayAll(charNow))
Dim rndString As String = ""
While rndGend < encLength
Randomize()
Dim genned As Integer = CInt(Math.Ceiling(Rnd() * 46)) + 1
charGenned = arrayAll(genned)
rndString = rndString + charGenned
rndGend += 1
End While
fs.Write(rndString & vbNewLine)
rndGend = 0
charNow = charNow + 1
genLength = genLength + 1
End While
据我所知,这应该给我我想要的结果,但是生成的字符串的长度根本不一致。输出示例:
alh*ph)lufe$2fz!d7c0$qfd(ol6f173#
b^i24@^v0gx%01iqrpugg8)(mqsl8%
c1km5jnz0hti&u$#rqeh5ism31t^96^
dkx&6$ok!@u#*e^x6659jpvcnn258zpi
e%y1(y3%@w9kk9&h7d6gw)w72*3c9*d)j
fy#(i4yeg0%ltj@887!x4!e32^703e4l
gj$4#5&f!!zzdkvs)v@@94)*rcmroy
虽然字母A之后的字符串长为32位,B和C一样,但是到G时,字符串只有29个字符长。最值得注意的是,该程序只会为最多5个数字的字符生成字符串,然后停止:
3%y1(y3%@w9kk9&h7d6gw)w72*3c9*d)j
4y#(i4yeg0%ltj@887!x4!e32^703e4l
5j$4#5&f!!zzdkvs)
这是怎么回事?
答案 0 :(得分:2)
我只是整理了一下,然后更改为Random类,我认为它更易于使用。如果在vb.net中声明数组,请记住它是Dim variable(ubound)As Type。 ubound代表数组的上限,即最高索引,因此具有47个元素的数组的索引为0-46。 ubound将是46 Dim变量(46)作为字符串
Private r As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Dim arrayLetters() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
Dim arrayAll() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")"}
Dim encLength As Integer = 16
If CheckBox2.Checked = True Then
encLength = 32
End If
Dim enhancedMode As Integer = 26
If CheckBox1.Checked = True Then
enhancedMode = 46
End If
Dim genLength As Integer = 0
Dim charNow As Integer = 0
Dim charGenned As String
Dim rndGend As Integer = 0
Dim sb As New StringBuilder
While genLength < enhancedMode
sb.Append(arrayAll(charNow))
Dim rndString As String = ""
While rndGend < encLength
Dim genned As Integer = r.Next(0, 46)
charGenned = arrayAll(genned)
rndString &= charGenned
rndGend += 1
End While
sb.AppendLine(rndString)
rndGend = 0
charNow += 1
genLength += 1
End While
Dim name As String
If TextBox1.Text = "" Then
name = "KeyGenned"
Else
name = TextBox1.Text
End If
Dim path As String = Application.StartupPath & "\" & name & ".txt"
File.WriteAllText(path, sb.ToString)
Close()
End Sub