How can I generate random alphanumeric strings?

后端 未结 30 3284
予麋鹿
予麋鹿 2020-11-22 03:17

How can I generate a random 8 character alphanumeric string in C#?

30条回答
  •  耶瑟儿~
    2020-11-22 03:54

    I was looking for a more specific answer, where I want to control the format of the random string and came across this post. For example: license plates (of cars) have a specific format (per country) and I wanted to created random license plates.
    I decided to write my own extension method of Random for this. (this is in order to reuse the same Random object, as you could have doubles in multi-threading scenarios). I created a gist (https://gist.github.com/SamVanhoutte/808845ca78b9c041e928), but will also copy the extension class here:

    void Main()
    {
        Random rnd = new Random();
        rnd.GetString("1-###-000").Dump();
    }
    
    public static class RandomExtensions
    {
        public static string GetString(this Random random, string format)
        {
            // Based on http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c
            // Added logic to specify the format of the random string (# will be random string, 0 will be random numeric, other characters remain)
            StringBuilder result = new StringBuilder();
            for(int formatIndex = 0; formatIndex < format.Length ; formatIndex++)
            {
                switch(format.ToUpper()[formatIndex])
                {
                    case '0': result.Append(getRandomNumeric(random)); break;
                    case '#': result.Append(getRandomCharacter(random)); break;
                    default : result.Append(format[formatIndex]); break;
                }
            }
            return result.ToString();
        }
    
        private static char getRandomCharacter(Random random)
        {
            string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            return chars[random.Next(chars.Length)];
        }
    
        private static char getRandomNumeric(Random random)
        {
            string nums = "0123456789";
            return nums[random.Next(nums.Length)];
        }
    }
    

提交回复
热议问题