views:

450

answers:

5

I need a method to return a random string in the format:

Letter Number Letter Number Letter Number

(C#)

+2  A: 

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.

Update

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.

Daok
Using that utility method is a very bad idea. You'll almost always get the same numbers in the string, and the same letters (e.g. B4B4B4), because you'll be creating 6 Randoms in very quick succession. You should only have one Random.
Jon Skeet
It's just a snippet... he can improve... it's to show him a way to do it... not VERY bad... and the earth will still turn around Jon... do not worry... this code haven't been done in VS but right from this website and might not be perfect.
Daok
I added an update for you Jon.
Daok
I wrote a better version see under this post, I made a new post, you like that better?
Daok
Not a lot - it may work, but it's unreadable (to me, anyway). It should come as no surprise that I find my own answer the most pleasant :)
Jon Skeet
Yeah and your fan club seem to like it too, one more answer accepted by you.
Daok
Doesn't seem to have been accepted yet...
Jon Skeet
I know, it's just weird to see that you are the only one here that still increase when I believe Hath answers or my new one should get some vote too. I think it's how this website is build that make vote up strange. Your solution is nice, but very big for this task...
Daok
I prefer a few more lines which are easy to modify and debug than short code which you need to read over very carefully before changing. Your answer and Hath's are both full of "magic numbers" - mine is (hopefully) very easy to understand and/or change.
Jon Skeet
(They'll both work, of course... I'm just saying I have reasons for writing the longer version.)
Jon Skeet
+10  A: 

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.

Jon Skeet
+1 for simple solution Jon... but I think you need to switch the RandomLetter with RandomDigit names.
bruno conde
wow, nice clean solution. Yeah a littler switcharoo on the letters/numbers.
Blankman
Oops - thanks. The "joys" of c'n'p
Jon Skeet
A: 

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...

Random Members

Michael Stum
+2  A: 
    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');
}
Hath
No need to if statements. Just increment i;
yapiskan
+1  A: 

Shorter version without any IF

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);
    }
}
Daok
nice. why do you need the Convert.ToInt32() will rand.Next(65 - (17 *(i % 2)), 90 - (33 * (i % 2))); not work?
Hath
I removed the Conver. You where right!
Daok