我的任务是在VB中编码转置密码,我决定路由密码是最容易实现的。我已经编写了矩阵的创建和创建密码的方法,但是,在从数组中提取密码时,我收到了意外的空白区域,可能用于在实例化时填充数组。请问您能告诉我如何解决这个问题,从而防止原始unciphered
字符串中没有空格?
Sub Main()
Console.Write("Please enter the string that you would like to encipher: ")
Dim Unciphered As String = Console.ReadLine()
Console.WriteLine("Unciphered = {0}", Unciphered)
Dim Length = Unciphered.Length()
Dim Rows = Math.Ceiling((Length / 4) * 3)
Dim Cols = Math.Ceiling(Length / 4)
Dim Matrix(Rows, Cols) As Char
Dim Idx As Integer = 0
For Row = 0 To Rows
For Column = 0 To Cols
If (Idx < Unciphered.Length) Then
Matrix(Row, Column) = Unciphered.Chars(Idx)
Idx += 1
End If
Next
Next
Console.WriteLine()
Console.WriteLine("Matrix: ")
Console.WriteLine()
For Column = 0 To Cols
For Row = 0 To Rows
Console.Write(Matrix(Row, Column))
Next
Console.WriteLine()
Next
Console.WriteLine()
Dim Ciphered As String = ""
For Column = 0 To Cols
For Row = 0 To Rows
Ciphered = String.Concat(Ciphered, Matrix(Row, Column))
Next
Next
Console.WriteLine("Ciphered string is: ")
Console.WriteLine()
Console.WriteLine(Ciphered)
Console.WriteLine()
Console.WriteLine("Length = {0}", Ciphered.Length)
Console.WriteLine()
Console.ReadLine()
End Sub
答案 0 :(得分:0)
数组是固定长度的。如果您的数据没有填满数组,您必须跟踪哪个索引构成数组的结尾,或者ReDim数组以适合数据。
更简单的解决方案是使用动态List(Of List(Of Char))。您以类似的方式访问它(Matrix(1)(3)
)但使用Count - 1作为循环的限制
填充矩阵将是这样的:
Dim Matrix As New List(Of List(Of Char))
For rows = 0 to Unciphered.Length-1 Step 4
For cols = 0 to 3
If (Unciphered.Length - 1) <= (rows + cols) Then
Matrix(rows).Add(Unciphered(rows + cols))
Else
Exit For
End If
Next
Next
现在矩阵没有填充。