如何生成随机字符串,并指定所需的长度,或者更好地生成所需的规范上的唯一字符串

问题描述 投票:34回答:8

有一个库可以生成随机数,那么为什么没有用于生成随机字符串的库?

换句话说,如何生成随机字符串,并指定所需的长度,或更好,在您想要的规范上生成唯一字符串,即指定长度,我的应用程序中的唯一字符串对我来说已经足够了。

我知道我可以创建一个Guid(全球唯一的标识符),但是它们需要更长,更长。

int length = 8;
string s = RandomString.NextRandomString(length)
uniquestringCollection = new UniquestringsCollection(length)
string s2 = uniquestringCollection.GetNext();
c# string random
8个回答
42
投票

我不记得我在哪里得到这个,所以如果你知道谁是最初撰写的,请帮助我给予归属。

private static void Main()
{
    const string AllowedChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()";
    Random rng = new Random();

    foreach (string randomString in rng.NextStrings(AllowedChars, (15, 64), 25))
    {
        Console.WriteLine(randomString);
    }

    Console.ReadLine();
}

private static IEnumerable<string> NextStrings(
    this Random rnd,
    string allowedChars,
    (int Min, int Max)length,
    int count)
{
    ISet<string> usedRandomStrings = new HashSet<string>();
    (int min, int max) = length;
    char[] chars = new char[max];
    int setLength = allowedChars.Length;

    while (count-- > 0)
    {
        int stringLength = rnd.Next(min, max + 1);

        for (int i = 0; i < stringLength; ++i)
        {
            chars[i] = allowedChars[rnd.Next(setLength)];
        }

        string randomString = new string(chars, 0, stringLength);

        if (usedRandomStrings.Add(randomString))
        {
            yield return randomString;
        }
        else
        {
            count++;
        }
    }
}

16
投票

怎么样-

    static Random rd = new Random();
    internal static string CreateString(int stringLength)
    {
        const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789!@$?_-";
        char[] chars = new char[stringLength];

        for (int i = 0; i < stringLength; i++)
        {
            chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
        }

        return new string(chars);
    }

3
投票

我通常使用如下代码生成随机字符串:

internal static class Utilities {
  static Random randomGenerator = new Random();
  internal static string GenerateRandomString(int length) {
    byte[] randomBytes = new byte[randomGenerator.Next(length)];
    randomGenerator.NextBytes(randomBytes);
    return Convert.ToBase64String(randomBytes);
  }
}

这将创建由随机对象生成的随机字节的Base64编码字符串。它不是线程安全的,因此多线程必须锁定它。另外,我使用静态Random对象,因此同时对方法的两次调用将不会获得相同的初始种子。


2
投票

用于生成随机字符串的库不是非常有用。它要么太简单了,要么你经常需要更换它,或者为了能够覆盖任何可能的情况而过于复杂,你要更换它,因为它使用起来很复杂。

根据您的需求的确切细节,通过将随机生成器用于数字,可以非常轻松地创建随机字符串。为每种情况专门编写代码会更有效率。

如果你想要一个独特的字符串,有两种可能性。您可以保留所创建的每个随机字符串,以便您可以检查唯一性,或者您可以将其设置为非常长,以便不可能存在重复项。 GUID执行后者(这解释了为什么它如此之长),因此已经有了实现。


1
投票

怎么样

string.Join("", Enumerable.Repeat(0, 100).Select(n => (char)new Random().Next(127))));

要么

var rand = new Random(); string.Join("", Enumerable.Repeat(0, 100).Select(n => (char)rand.Next(127))));


0
投票

你有点回答你自己的问题;没有RandomString()函数,因为您可以使用随机数生成器轻松生成字符串。

1)在您希望包含的ASCII字符之间设置数字范围

2)将每个字符附加到字符串,直到达到所需的长度。

3)上升并重复所需的每个字符串(将它们添加到数组等)

当然那样做了吗?


0
投票

这样的事情怎么样......

static string GetRandomString(int lenOfTheNewStr)
{
    string output = string.Empty;
    while (true)
    {
        output = output + Path.GetRandomFileName().Replace(".", string.Empty);    
        if (output.Length > lenOfTheNewStr)
        {
            output = output.Substring(0, lenOfTheNewStr);
            break;
        }
    }
    return output;
}

产量

static void Main(string[] args)
{            
    for (int x = 0; x < 10; x++)
    {
        string output = GetRandomString(20);
        Console.WriteLine(output);
    }
    Console.ReadKey();
}

r323afsluywgozfpvne4
qpfumdh3pmskleiavi3x
nq40h0uki2o0ptljxtpr
n4o0rzwcz5pdvfhmiwey
sihfvt1pvofgxfs3etxg
z3iagj5nqm4j1f5iwemg
m2kbffbyqrjs1ad15kcn
cckd1wvebdzcce0fpnru
n3tvq0qphfkunek0220d
ufh2noeccbwyfrtkwi02

在线演示:https://dotnetfiddle.net/PVgf0k


参考 •https://www.dotnetperls.com/random-string


0
投票

使用连接GUID的随机字符串

此方法使用最小数量的连接GUID返回所需字符数的随机字符串。

    /// <summary>
    /// Uses concatenated then SubStringed GUIDs to get a random string of the
    /// desired length. Relies on the randomness of the GUID generation algorithm.
    /// </summary>
    /// <param name="stringLength">Length of string to return</param>
    /// <returns>Random string of <paramref name="stringLength"/> characters</returns>
    internal static string GetRandomString(int stringLength)
    {
        StringBuilder sb = new StringBuilder();
        int numGuidsToConcat = (((stringLength - 1) / 32) + 1);
        for(int i = 1; i <= numGuidsToConcat; i++)
        {
            sb.Append(Guid.NewGuid().ToString("N"));
        }

        return sb.ToString(0, stringLength);
    }

长度为8的示例输出:

39877037
2f1461d8
152ece65
79778fc6
76f426d8
73a27a0d
8efd1210
4bc5b0d2
7b1aa10e
3a7a5b3a
77676839
abffa3c9
37fdbeb1
45736489

长度为40的示例输出(注意重复的'4' - 在v4 GUID中,你是一个十六进制数字,总是一个4(有效地删除4位) - 可以通过删除'4'来改进算法为了提高随机性,假设字符串的返回长度可以小于GUID的长度(32个字符)...):

e5af105b73924c3590e99d2820e3ae7a3086d0e3
e03542e1b0a44138a49965b1ee434e3efe8d063d
c182cecb5f5b4b85a255a397de1c8615a6d6eef5
676548dc532a4c96acbe01292f260a52abdc4703
43d6735ef36841cd9085e56f496ece7c87c8beb9
f537d7702b22418d8ee6476dcd5f4ff3b3547f11
93749400bd494bfab187ac0a662baaa2771ce39d
335ce3c0f742434a904bd4bcad53fc3c8783a9f9
f2dd06d176634c5b9d7083962e68d3277cb2a060
4c89143715d34742b5f1b7047e8107fd28781b39
2f060d86f7244ae8b3b419a6e659a84135ec2bf8
54d5477a78194600af55c376c2b0c8f55ded2ab6
746acb308acf46ca88303dfbf38c831da39dc66e
bdc98417074047a79636e567e4de60aa19e89710
a114d8883d58451da03dfff75796f73711821b02

C#Fiddler演示:https://dotnetfiddle.net/Y1j6Dw

© www.soinside.com 2019 - 2024. All rights reserved.