由于我还没有使用过那些旧的 VB 函数,我将向您展示如何使用 VB.NET 来完成它,它也可以很容易地转换为 C#:
Private Function RandomString(rnd As Random, size As Integer) As String
Dim chars() 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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim builder As New System.Text.StringBuilder()
For i As Integer = 0 To size - 1
builder.Append(chars(rnd.Next(0, chars.Length)))
Next
Return builder.ToString()
End Function
让我们生成一个包含 5 个字符的随机字符串:
Dim rnd = New Random()
Dim rndString = RandomString(rnd, 5)
请注意,我正在传递随机实例。如果我将在方法中创建它并在循环中调用它,它将生成相同的字符串,因为Random
它将使用与种子相同的时间。
编辑:我刚刚看到你需要分离结果。您可以使用重载版本:
Private Overloads Function RandomString(rnd As Random, size As Integer, separator As String, everyNChar As Int32) As String
Dim builder = New System.Text.StringBuilder()
Dim chars() 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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
For i As Integer = 0 To size - 1
If i > 0 AndAlso i Mod everyNChar = 0 Then
builder.Append(chars(rnd.Next(0, chars.Length))).Append(separator)
Else
builder.Append(chars(rnd.Next(0, chars.Length)))
End If
Next
Return builder.ToString()
End Function
请注意,这不会计算分隔符。