Skip to content

Instantly share code, notes, and snippets.

@SamVanhoutte
Created January 22, 2015 10:36
Show Gist options
  • Save SamVanhoutte/808845ca78b9c041e928 to your computer and use it in GitHub Desktop.
Save SamVanhoutte/808845ca78b9c041e928 to your computer and use it in GitHub Desktop.
Random string generator, based on format
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)];
}
}
@SamVanhoutte
Copy link
Author

This extension method (on Random) allows to generate a random string, in the format of your choice. This was added as a solution on StackOverflow: http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment