-5

I want to create a function that returns a random string of numbers and letters, In form (2 letters + 4 numbers + 2 letters) Example AD1256Cv

KAMAL96
  • 37
  • 1
  • 3
  • 8

5 Answers5

4

Use this-

private string RandomString()
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var numbers = "0123456789";
            var stringChars = new char[8];
            var random = new Random();

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

            var finalString = new String(stringChars);
            return finalString;
        }
LogicalDesk
  • 1,237
  • 4
  • 16
  • 46
2

I guess I'll throw my two cents in here. Basically, I'm using ASCII to select either an uppercase letter, a lowercase letter, or a number. The important insight is that you can cast an integer to a char if the number corresponds to a printable ASCII character; for example, (char)97 is 'a'.

public void PrintRandom() {
   Random r = new Random();
   // Decide how long the string will be
   int strLength = r.Next(1, 10);

   var sb = new StringBuilder();

   for (int i = 0; i < strLength; i++) {
      // Decide whether to add an uppercase letter, a lowercase letter, or a number
      int whichType = r.Next(0, 3);
      switch (whichType) {
        // Lower case letter
        case 0: sb.Append((char)(97 + r.Next(0, 26)));
          break;
        // Upper case letter
        case 1: sb.Append((char)(65 + r.Next(0, 26)));
           break;
        // Number
        case 2:
           sb.Append((char)(48 + r.Next(0, 10)));
           break;
      }
   }

   Console.WriteLine(sb.ToString());
   Console.ReadLine();
}
  • 1
    my answer is less lines of code... just ignore the fact that my lines are longer. I like your approach, it's pretty easy to read and follow. I'd probably vote this the best answer. – Joe_DM Jul 14 '17 at 15:54
0

One simple way would be using the fact that digits and letters are contiguosly arranged in the character encoding (such as ASCII etc.)

var rand = new Random();
var arr = new char[] {
        (char)rand.Next('A', 'Z'), 
        (char)rand.Next('A', 'Z'), 
        (char)rand.Next('0', '9'),
        (char)rand.Next('0', '9'),
        (char)rand.Next('0', '9'),
        (char)rand.Next('0', '9'),
        (char)rand.Next('A', 'Z'),
        (char)rand.Next('A', 'Z')};
var randStr = new string(arr);
Console.WriteLine(arr);

This would not work for mixed uppercase and lowercase letters though, since these are not contiguously next to each other.

adjan
  • 13,371
  • 2
  • 31
  • 48
0

some clues to get you started

Generate a random number between 0 and 25. see How do I generate a random int number in C#?

int rand = randomNumber(0, 25);

pick that element from an array of characters

var randchar = "abcdefghij.....z"[rand];

you now have one random character. Repeat, do a similar thing for digits, repeat, etc.

pm100
  • 48,078
  • 23
  • 82
  • 145
  • The string should include uppercase letters and numbers, too (plus presumably a random string length). – EJoshuaS - Stand with Ukraine Jul 14 '17 at 15:26
  • 3
    I assume the questioner can work that out . If not then all is lost anyway – pm100 Jul 14 '17 at 15:27
  • True. I suppose that giving them the code is the wrong answer to a "gimme teh codez" question anyway (which the question currently is). – EJoshuaS - Stand with Ukraine Jul 14 '17 at 15:28
  • this only addresses how to generate a random number, it does nothing to instruct the op how to map this to ASCII or convert a number into a character. I'm pretty confident the op could work out how to generate a random number with a quick search, they just need some guidance on how a random number can map into a random letter and how a lower case and an upper case are different. (e.g. how flipping the 6th bit can toggle caseing) – Joe_DM Jul 14 '17 at 15:58
  • @Joe_DM my second code snippet shows how to make a letter from the random number. In general I prefer not to write code for people but instead to provide pointers to how to get started. If they cannot work out how to extend this to cover a-z and A-Z then they are not going to succeed in much programming anyway – pm100 Jul 14 '17 at 20:02
0
Random rndGenerator = new Random();
StringBuilder myRandomString = new StringBuilder();

for (int i = 0; i < 10; i++) // set how many random characters we want to generate
{
    bool isAlpha = Convert.ToBoolean(rndGenerator.Next(0, 2));
    int rndNumber = isAlpha ? rndGenerator.Next(0, 26) : rndGenerator.Next(0, 10); // set the boundry 26 letters in alphabet, 10 numbers
    if (isAlpha)
    {
        bool isUpper = Convert.ToBoolean(rndGenerator.Next(0, 2));
        rndNumber += isUpper ? 65 : 97; // add an offset of 65 which gets us to an A in the ASCII table, 97 is same for a
    }

    myRandomString.Append(isAlpha ? ((char)rndNumber).ToString() : rndNumber.ToString() );
}

Console.WriteLine(myRandomString.ToString());
Joe_DM
  • 985
  • 1
  • 5
  • 12