我正在尝试在 VB.net 中创建一个循环算法的函数。我已经使用 Split 命令将算法拆分为一个数组,所以我有一个包含值的数组。然后我尝试遍历它们并在必要时用“数字”替换 #,但是 VB.net 会引发错误。我对 VB.net 还很陌生,所以我不确定它为什么要这样做。算法的格式为A B C D E F 1 2 3 #
Function generate(ByVal alg As String)
Dim algSplit As String() = alg.Split(" ")
For Each digit In algSplit
Dim replacement As String = algSplit(digit).Replace("#", "Number")
algSplit(digit) = replacement
Next
Dim result As String = String.Join("", algSplit)
MsgBox(result)
End Function
有快速修复吗?
问题第 2 部分:我让循环正常工作;但是我破坏了我想要的部分功能。
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
Dim Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max)
End Function
Public Function RandLet() As String
Dim number As Integer = GetRandom(1, 26)
Dim Alphabet() As String = New 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 Letter As String = Alphabet(number)
Return Letter
End Function
Function generate(ByVal alg As String) As String
Dim algSplit As String() = alg.Split(" "c)
For index As Int32 = 0 To algSplit.Length - 1
algSplit(index) = algSplit(index).Replace("#"c, GetRandom(1, 9)).Replace("%"c, RandLet())
Next
Dim result As String = String.Join("", algSplit)
MsgBox(result)
Return result
End Function
最终结果从A B C D E F 1 2 3 | L % % % | N # # #
本质ABCDEF123|LXXX|N888
上讲,每个 # 和每个 % 都被相同的数字替换,而不是每次都替换为不同的数字。我以为在循环中不会发生这种情况,我错过了什么?