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

前端 未结 11 2323
一生所求
一生所求 2020-12-24 06:24

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 sp

相关标签:
11条回答
  • 2020-12-24 07:01

    You've sort of answered your own question; there is no RandomString() function because you can use a random number generator to generate a string easily.

    1) Make the range of numbers between the ASCII characters that you wish to include

    2) Append each character to a string until the desired length is reached.

    3) Rise and repeat for each string needed (add them to an array, etc.)

    Surely that'd do it?

    0 讨论(0)
  • 2020-12-24 07:06

    A library for generating random strings wouldn't be very useful. It would either be too simple, so that you often need to replace it anyway, or too complex in order to be able to cover any possible situation, that you replace it because it's to complicated to use.

    Creating random strings is quite easy by using the random geneator for numbers, given the exact details of your needs. It's just more efficient to write the code specifically for each situation.

    If you want a unique string, there is two possibilities. You can either keep every random string that is created, so that you can check for uniqueness, or you can make it really long so that it's incredibly unlikely that there would be duplicates. A GUID does the latter (which explains why it's so long), so there is already an implementation for that.

    0 讨论(0)
  • 2020-12-24 07:09

    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

    0 讨论(0)
  • 2020-12-24 07:10

    Here is some modification from above answers.

      private static string GetFixedLengthStrinng(int len)
        {
            const string possibleAllChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789!@#$%^&*()_+{}:',.?/";
            StringBuilder sb = new StringBuilder();
            Random randomNumber = new Random();
            for (int i = 0; i < len; i++)
            {
                sb.Append(possibleAllChars[randomNumber.Next(0, possibleAllChars.Length)]);
            }
            return sb.ToString();
        }
    
    0 讨论(0)
  • 2020-12-24 07:12

    I commonly use code like the following to generate a random string:

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

    This will create a Base64 encoded string of the random bytes generated by the random object. It isn't thread safe so multiple threads will have to lock around it. Additionally I use a static Random object so two calls to the method at the same time won't get the same initial seed.

    0 讨论(0)
  • 2020-12-24 07:14

    How about something like this...

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

    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
    

    Online Demo: https://dotnetfiddle.net/PVgf0k


    References
    • https://www.dotnetperls.com/random-string

    0 讨论(0)
提交回复
热议问题