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.
Random.NextDouble()
method to generate a float (flt
) that is between and and is inclusive.flt
with and take the Floor
of the result. This will return an integer (shift
) that is between and and is inclusive.shift
integer to , which is the ASCII value of the character A. This will return an inclusive value between and , which will be the ASCII value of some character. Converting that value to a character will return an uppercase character.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());}}
Free Resources