Search code examples
c#stringrandom

How to generate a random string, and specify the length you want, or better generate unique string on specification you want


There is a library to generate Random numbers, so why isn't there a library for generation of random strings?

In other words how to generate a random string, and specify desired length, or better, generate unique string on specification you want i.e. specify the length, a unique string within my application is enough for me.

I know I can create a Guid (Globally Unique IDentifier) but those are quite long, longer they need to be.

int length = 8;
string s = RandomString.NextRandomString(length)
uniquestringCollection = new UniquestringsCollection(length)
string s2 = uniquestringCollection.GetNext();

Solution

  • I can't recall where I got this, so if you know who originally authored this, please help me give attribution.

    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++;
            }
        }
    }