随机字符串发生器返回相同的字符串 [英] Random String Generator Returning Same String

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

问题描述

我已经开发了一个随机字符串生成器,但它没有表现相当因为我希望。我的目标是能够运行两次这一点,并产生两个不同的四个字符的随机字符串。然而,它只是产生两次四位一体字符随机字符串。

I've developed a random string generator but it's not behaving quite as I'm hoping. My goal is to be able to run this twice and generate two distinct four character random strings. However, it just generates one four character random string twice.

这里的code,其输出的例子:

Here's the code and an example of its output:

private string RandomString(int size)
{
    StringBuilder builder = new StringBuilder();
    Random random = new Random();
    char ch;
    for (int i = 0; i < size; i++)
    {
        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));                 
        builder.Append(ch);
    }

    return builder.ToString();
}

// get 1st random string 
string Rand1 = RandomString(4);

// get 2nd random string 
string Rand2 = RandomString(4);

// create full rand string
string docNum = Rand1 + "-" + Rand2;

...和输出如下所示:UNTE-UNTE
...但它应该是这个样子UNTE-FWNU

...and the output looks like this: UNTE-UNTE ...but it should look something like this UNTE-FWNU

我如何才能确保两个截然不同的随机字符串?

How can I ensure two distinctly random strings?

推荐答案

您正在做随机实例中的方法,这会导致它在快速连续调用时返回的值相同。我会做这样的事情:

You're making the Random instance in the method, which causes it to return the same values when called in quick succession. I would do something like this:

private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
private string RandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));                 
            builder.Append(ch);
        }

        return builder.ToString();
    }

// get 1st random string 
string Rand1 = RandomString(4);

// get 2nd random string 
string Rand2 = RandomString(4);

// creat full rand string
string docNum = Rand1 + "-" + Rand2;

(您code的修改版)

(modified version of your code)

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

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