I need a method to return a random string in the format:
Letter Number Letter Number Letter Number
(C#)
I need a method to return a random string in the format:
Letter Number Letter Number Letter Number
(C#)
You just need 2 methods.
1) Random a char (You can use ASCII to random between number than cast to char)
2) Random number.
Both can use this utility method:
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
For the letter you need to call RandomNumber(65,90);
and for the number you call : RandomNumber(1,9);
You just need to concatenate.
Than you call these methods to create your string, Hope this help you.
You should put the random object in your class... it was just to show you how to do it. You still need to work a little but I think it's a good start to show you how to manipulate char from ascii.
Assuming you don't need it to be threadsafe:
private static readonly Random rng = new Random();
private static RandomChar(string domain)
{
int selection = rng.Next(domain.Length);
return domain[selection];
}
private static char RandomDigit()
{
return RandomChar("0123456789");
}
private static char RandomLetter()
{
return RandomChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
public static char RandomStringInSpecialFormat()
{
char[] text = new char[6];
char[0] = RandomLetter();
char[1] = RandomDigit();
char[2] = RandomLetter();
char[3] = RandomDigit();
char[4] = RandomLetter();
char[5] = RandomDigit();
return new string(text);
}
(You could use a 3-iteration loop in RandomStringInSpecialFormat, but it doesn't have much benefit.)
If you need it to be thread-safe, you'll need some way of making sure you don't access the Random from multiple threads at the same time. The simplest way to do this (in my view) is to use StaticRandom from MiscUtil.
Then just use the Random.NextBytes function together with Encoding.ASCII.GetString() to generate Characters.
Or, alternatively, generate a String or char Array (string[]) and use Random.Next(0,array.Length) to get an index to it.
Use a StringBuilder and Random.Next(0,9) to generate numbers and then generate your string by adding a number, a character, a numer etc...
public static string RandomString(Random rand, int length)
{
char[] str = new char[length];
for (int i = 0; i < length; i++)
{
if (i % 2 == 0)
{ //letters
str[i] = (char)rand.Next(65, 90);
}
else
{
//numbers
str[i] = (char)rand.Next(48, 57);
}
}
return new string(str);
}
maybe this would be more readable...
if (i % 2 == 0)
{
//letters
str[i] = (char)rand.Next('A', 'Z');
}
else
{
//numbers
str[i] = (char)rand.Next('0', '9');
}
class Program
{
static void Main(string[] args)
{
Random r = new Random();
for(int i = 0;i<25;i++)
Console.WriteLine(RandomString(r,6));
Console.Read();
}
public static string RandomString(Random rand, int length)
{
char[] str = new char[length];
for (int i = 0; i < length; i++)
str[i] = (char)rand.Next(65 - (17 * (i % 2)), 91-(33 * (i % 2)));
return new string(str);
}
}