Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

generate
random
string
c#

How to generate a random string in C#

Educative Answers Team

Generating a random string in C# uses the same concepts that are used to generate a random number in C#. The StringBuilder class and the NextDouble() method in the Random class are used to generate a random string.

Algorithm

  • Use the Random.NextDouble() method to generate a float (flt) that is between 0.00.0 and 1.01.0 and is inclusive.
  • Multiply flt with 2525 and take the Floor of the result. This will return an integer (shift) that is between 00 and 2525 and is inclusive.
  • Add the shift integer to 6565, which is the ASCII value of the character A. This will return an inclusive value between 6565 and 9090, which will be the ASCII value of some character. Converting that value to a character will return an uppercase character.
  • Repeat the above steps​ as required to obtain a randomly generated string.
svg viewer

Code

The code snippet below illustrates the algorithm described above:

using System.Text;
using System;
class GenerateRandomString
{
    static void Main()
    {
      int length = 7;
      
      // creating a StringBuilder object()
      StringBuilder str_build = new StringBuilder();  
      Random random = new Random();  

      char letter;  

      for (int i = 0; i < length; i++)
      {
        double flt = random.NextDouble();
        int shift = Convert.ToInt32(Math.Floor(25 * flt));
        letter = Convert.ToChar(shift + 65);
        str_build.Append(letter);  
      }  
      System.Console.WriteLine(str_build.ToString());
    }
}

RELATED TAGS

generate
random
string
c#
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring