Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

random

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();
like image 488
HCP Avatar asked Jan 06 '11 15:01

HCP


People also ask

How do you generate unique random strings?

There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.


4 Answers

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++;
        }
    }
}
like image 158
Jesse C. Slicer Avatar answered Oct 17 '22 13:10

Jesse C. Slicer


How about-

    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);
    }
like image 20
Jason Quinn Avatar answered Oct 17 '22 13:10

Jason Quinn


How about

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

or

var rand = new Random();
string.Join("", Enumerable.Repeat(0, 100).Select(n => (char)rand.Next(127)));
like image 8
Ali Humayun Avatar answered Oct 17 '22 14:10

Ali Humayun


Random string using Concatenated GUIDs

This approach uses the minimum number of concatenated GUIDs to return a random string of the desired number of characters.

    /// <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);
    }

Example output with a length of 8:

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

Example output with a length of 40 (note the repeated '4' - in a v4 GUID, thee is one hex digit that will always be a 4 (effectively removing 4 bits) -- the algorithm could be improved by removing the '4' to improve randomness, given that the returned length of the string can be less than the length of a GUID (32 chars)...):

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

C# Fiddler Demo: https://dotnetfiddle.net/Y1j6Dw

like image 6
CJBS Avatar answered Oct 17 '22 15:10

CJBS