生成随机字符串数组 [英] Generating an array of random strings

查看:46
本文介绍了生成随机字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个由随机生成的特定长度字符串组成的静态数组.我已经基于这里到目前为止的内容,但是每个索引都在该数组具有相同的字符串,而不是不同的字符串.我做错了什么?

I'm trying to build a static array of randomly generated strings of a specific length. I've based what I have so far from here, but each index in the array has the same string, instead of a different strings. What am I doing wrong?

Dim Target As String
 Target = InputBox("Input target string")

  Dim StringArray(10) As String
        For i = 1 To 10
            StringArray(i) = GenerateString(Len(Target))
            Debug.Print(StringArray(i))
        Next

  Function GenerateString(size As Integer) As String
        Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        Dim Rnd As New Random()
        Dim Builder As New System.Text.StringBuilder()
        Dim Ch As Char

        For i As Integer = 0 To size - 1
            Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
            Builder.Append(Ch)
        Next

        Return Builder.ToString()
    End Function

推荐答案

这个:Dim Rnd As New Random() 是错误发生的地方.

This: Dim Rnd As New Random() is where the error happens.

当你实例化一个新的 Random() 时,它以当前时间作为种子.由于您在每次迭代中再次实例化它并且所有迭代步骤都在相同"时间(非常快的连续)发生,因此每个 Random() 生成相同的输出.

When you instantiate a new Random(), it takes the current time as seed. Since you instantiate it again in every iteration AND all the iteration steps happen at the "same" time (in very fast succession), each Random() generates the same output.

您必须在迭代器之前将其实例化一次并将其作为参数传递到函数中,或者您也可以将其设为类的静态属性.

You have to instantiate it once before the iterator and pass it in the function as argument or you could also make it a static property of the class.

TL;DR:您将不得不重复使用相同的 Random() 而不是为每次迭代创建一个新的.

TL;DR: You will have to re-use the same Random() instead of creating a new one for each iteration.

这应该是正确的代码:

Dim Target As String
Target = InputBox("Input target string")

Dim StringArray(10) As String
    Dim Rnd As New Random()
    For i = 1 To 10
        StringArray(i) = GenerateString(Len(Target), Rnd)
        Debug.Print(StringArray(i))
    Next

 Function GenerateString(size As Integer, Rnd as Random) As String
    Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    Dim Builder As New System.Text.StringBuilder()
    Dim Ch As Char

    For i As Integer = 0 To size - 1
        Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
        Builder.Append(Ch)
    Next

    Return Builder.ToString()
End Function

这篇关于生成随机字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆