Created
January 22, 2015 10:36
-
-
Save SamVanhoutte/808845ca78b9c041e928 to your computer and use it in GitHub Desktop.
Random string generator, based on format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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