生成随机字符串 [英] Generate random string

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

问题描述

  

可能重复:
   C#随机字符串发生器

我需要生成一个随机字符串与给定的长度。这是我的code为止。问题是随机的字符串是像RRRRRR或每次SSSSS同样的信。就在我重新启动应用程序,这封信的变化。我需要的东西,如asrDvgDgREGd

 公共字符串GenerateChar()
    {
        随机随机=新的随机();

        返回Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble()+ 65)))的ToString();
    }

    公共字符串GenerateChar(诠释计数)
    {
        字符串randomString =;

        的for(int i = 0; I<计数;我++)
        {
            nahodneZnaky + = GenerateChar();
        }

        返回randomString;
    }
 

解决方案

尝试使用相同的随机对象的整个字符串,而不是初始化一个用于每个字符。

随机对象将产生一个伪随机数的基础上,从一个种子编号开始的数学级数。实际上,你可以得到的随机数相同的序列,如果你每次初始化随机对象相同的种子。

现在,当你初始化随机不指定一个种子,它会以计算机时钟作为种子。在这种情况下,你可能做的不够快,时钟并没有从一个初始化到另一个改变,你会得到总是得到相同的种子。

你最好在初始化你的函数随机对象,生成随机字符串,并且将它作为参数传递给GenerateChar功能,让你打电话NextDouble()多次在随机的同一个实例对象,而不是仅一次在它的不同的实例。

Possible Duplicate:
c# random string generator

I need to generate a random string with a given length. This is my code so far. The problem is the random string is like "RRRRRR" or "SSSSS" The same letter every time. Just when i restart the app the letter change. I need something like "asrDvgDgREGd"

    public string GenerateChar()
    {
        Random random = new Random();

        return Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))).ToString();
    }

    public string GenerateChar(int count)
    {        
        string randomString = "";

        for (int i = 0; i < count; i++)
        {
            nahodneZnaky += GenerateChar();
        }

        return randomString;
    }

解决方案

Try using the same random object for the whole string, rather than initializing one for each char.

The random object will generate a "pseudo-random" number, based on mathematical progressions starting from a "seed" number. You can actually get the same sequence of "random" numbers if you initialize the Random object to the same seed every time.

Now, when you initialize Random without specifying a seed, it'll take the computer's clock as seed. In this case, you're probably doing it fast enough that the clock hasn't changed from one initialization to another, and you get always get the same seed.

You're better off initializing the Random object in your function that generates the random string, and passing it as a parameter to the GenerateChar function, so that you're calling NextDouble() several times on the same instance of the Random object, instead of only once on different instances of it.

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

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