How to create formatted alphabetic numeric strings in C #

I want to generate a random string with 5 characters of alphabet letters, but must generate two characters and the other must be numeric, for example

 RL589

      

For this I did as

        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var stringChars = new char[5];
        var random = new Random();

        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[random.Next(chars.Length)];
        }

        var finalString = new String(stringChars);

      

But I am confused how to arrange the first two letters by symbols and the next other should be numeric. Please help me everyone.

+3


source to share


5 answers


Use two loops, for example:



var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var stringChars = new char[5];
var random = new Random();

for (int i = 0; i < 2; i++)
{
  stringChars[i] = chars[random.Next(chars.Length)];
}
for (int i = 2; i < stringChars.Length; i++)
{
  stringChars[i] = numbers[random.Next(numbers.Length)];
}

var finalString = new String(stringChars);

      

+2


source


Create two lines. One of the symbols and one of the numbers. Then put them together.



+4


source


var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";

var stringChars = new char[5];

var random = new Random();

for (int i = 0; i < stringChars.Length; i++)
{
    if (i < 2)
    {
        stringChars[i] = letters[random.Next(letters.Length)];
    }
    else
    {
        stringChars[i] = numbers[random.Next(numbers.Length)];
    }
}

var finalString = new String(stringChars);

      

0


source


You don't need any lines. Just use implicit conversions between char

and int

:

var stringChars = new char[5];
var random = new Random();

for (int i = 0; i < 2; i++)
{
    stringChars[i] = (char)random.Next('A', 'Z');
}
for (int i = 2; i < 5; i++)
{
    stringChars[i] = (char)random.Next('0', '9');
}

var finalString = new String(stringChars);

      

0


source


Why don't you just use the Random object to generate a random number?

var stringChars = new StringBuilder();
var random = new Random();

for (int i = 0; i < 2; i++)
{
    stringChars.Append((char)random.Next('A', 'Z'));
}

var finalString = string.Format("{0}{1}{2}{3}", stringChars.ToString()
    , random.Next(1, 9)
    , random.Next(1, 9)
    , random.Next(1, 9));

      

or simply

var finalString = string.Format("{0}{1}", stringChars.ToString()
        , random.Next(100, 999));

      

Why is StringBuilder, string concatenation always creates a new instance, so you should avoid that.

0


source







All Articles