C# 生成随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1572733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:58:41  来源:igfitidea点击:

Generate random string

c#.net

提问by user137348

Possible Duplicate:
c# random string generator

可能的重复:
c# 随机字符串生成器

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"

我需要生成一个给定长度的随机字符串。到目前为止,这是我的代码。问题是随机字符串每次都像“RRRRRR”或“SSSSS”一样的字母。就在我重新启动应用程序时,字母发生了变化。我需要类似“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;
    }

采纳答案by Daniel Magliola

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.

随机对象将生成一个“伪随机”数,基于从“种子”数开始的数学级数。如果每次都将 Random 对象初始化为相同的种子,则实际上可以获得相同的“随机”数字序列。

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.

现在,当您在不指定种子的情况下初始化 Random 时,它将以计算机的时钟作为种子。在这种情况下,您可能做得足够快,以至于时钟没有从一个初始化更改为另一个初始化,并且您总是得到相同的种子。

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.

您最好在生成随机字符串的函数中初始化 Random 对象,并将其作为参数传递给 GenerateChar 函数,以便您在 Random 对象的同一实例上多次调用 NextDouble(),而不是在它的不同实例上只有一次。

回答by Jon Skeet

Don't create a new instance of Randomon each iteration - that's going to seed each instance with the current time in milliseconds, which obviously isn't likely to change between iterations.

不要Random在每次迭代中创建一个新实例- 这将使用当前时间(以毫秒为单位)为每个实例播种,这显然不可能在迭代之间改变。

Create a single instance of Random, and pass it into the method. I'd also advise you not to concatenate strings like that in a loop, or even to create that many strings. Additionally, if you use Random.Next(int, int)to make your life a lot easier.

创建 的单个实例Random,并将其传递给方法。我还建议您不要在循环中连接这样的字符串,甚至不要创建那么多字符串。此外,如果您使用Random.Next(int, int)使您的生活更轻松。

Try this:

尝试这个:

public char GenerateChar(Random rng)
{
    // 'Z' + 1 because the range is exclusive
    return (char) (rng.Next('A', 'Z' + 1));
}

public string GenerateString(Random rng, int length)
{ 
    char[] letters = new char[length];
    for (int i = 0; i < length; i++)
    {
        letters[i] = GenerateChar(rng);
    }
    return new string(letters);
}

private static readonly Random SingleRandom = new Random();

public string GenerateStringNotThreadSafe(int length)
{ 
    return GenerateString(SingleRandom, length);
}

Now it's worth being aware that Randomisn't thread-safe, so if you've got multiple threads you shouldn't just have a single instance of Randomin a static variable without locking. There are various ways around this - either create a subclass of Randomwhich isthread-safe, or a set of static methods which do the same thing, or use thread-local variables to have one instance per thread.

现在值得注意的是这Random不是线程安全的,所以如果你有多个线程,你不应该Random在没有锁定的情况下在静态变量中只有一个实例。这种情况有解决各种方式-无论是创建一个子类的Random线程安全的,或一组静态方法里面做同样的事情,或使用线程局部变量有每线程一个实例。

I have a StaticRandomclassas part of MiscUtilbut these days I'm leaning towards the thread-local version and passing it down the chain where appropriate. One day I'll add that as another option to MiscUtil...

我有一个StaticRandom作为MiscUtil 的一部分,但最近我倾向于使用线程本地版本并在适当的情况下将其传递到链中。有一天,我会将其添加为 MiscUtil 的另一种选择...

回答by penderi

Pass randomfrom the calling method and initialise it once - you are reseeding the Random generator with the same seed each time....

random从调用方法传递并初始化一次 - 您每次都使用相同的种子重新播种随机生成器......

回答by Paulo Guedes

You should initialize your random variable outside the method:

您应该在方法之外初始化您的随机变量:

public Random random = new Random();

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

...

回答by James

You could save yourself the hassle and use Membership.GeneratePasswordmethod. It is essentially doing what you require.

您可以省去麻烦并使用Membership.GeneratePassword方法。它本质上是在做你需要的。

Usage:

用法:

int passwordLength = 5;
int alphaNumericalCharsAllowed = 2;
string random = Membership.GeneratePassword(passwordLength, alphaNumericalCharsAllowed);

For readability aswell you could wrap this in a helper method:

为了便于阅读,您可以将其包装在辅助方法中:

private string GenerateRandomString(int length, int alphaNumericalChars)
{
      return Membership.GeneratePassword(length, alphaNumericalChars);
}

回答by Konamiman

Maybe you can find the Path.GetRandomFileNamemethod useful, depending on the exact characters you need in the string.

也许您会发现该Path.GetRandomFileName方法很有用,具体取决于字符串中所需的确切字符。

回答by Pavel Yakimenko

Try static

尝试静态

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

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

回答by Tubbe

I know this might not be the best solution, but I kind of like the idea to be able to specify "allowed" characters:

我知道这可能不是最好的解决方案,但我有点喜欢能够指定“允许”字符的想法:

    private const int _defaultNumberOfCharacters = 8;
    private const int _defaultExpireDays = 10;
    private static readonly string _allowedCharacters = "bcdfghjklmnpqrstvxz0123456789";

    public static string GenerateKey(int numberOfCharacters)
    {
        const int from = 0;
        int to = _allowedCharacters.Length;
        Random r = new Random();

        StringBuilder qs = new StringBuilder();
        for (int i = 0; i < numberOfCharacters; i++)
        {
            qs.Append(_allowedCharacters.Substring(r.Next(from, to), 1));
        }
        return qs.ToString();
    }

回答by Kamarey

Nothing special, but short. 32 and 127 are min and max range of chars you want to be generated.

没什么特别的,但很短。32 和 127 是您要生成的字符的最小和最大范围。

public static string GetRandomString(int length)
{
    var r = new Random();
    return new String(Enumerable.Range(0, length).Select(n => (Char)(r.Next(32, 127))).ToArray());
}

回答by juFo

http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx

http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx

string randomName = Path.GetRandomFileName();
randomName = randomName.Replace(".", string.Empty);

// take substring...