How to generate a string randomly using C#?


Firstly, set a string.

StringBuilder str = new StringBuilder();

Use Random.

Random random = new Random((int)DateTime.Now.Ticks);

Now loop through a number which is the length of the random string you want.

for (int i = 0; i < 4; i++) {
   c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
   str.Append(c);
}

On every iteration above, a random character is generated and appended to form a string.

The following is the complete example −

Example

 Live Demo

using System.Text;
using System;
class Program {
   static void Main() {
      StringBuilder str = new StringBuilder();
      char c;
      Random random = new Random((int)DateTime.Now.Ticks);
      for (int i = 0; i < 4; i++) {
         c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
         str.Append(c);
      }
      Console.WriteLine(str.ToString());
   }
}

Output

ATTS

Updated on: 22-Jun-2020

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements