C# - Randomly Generating Strings - GeeksforGeeks

06 Dec, 2021
In C#, a string is a sequence of Unicode characters or an array of characters. The range of Unicode characters will be U+0000 to U+FFFF. A string is the representation of the text.   In this article, we will learn how to randomly generate strings and alphanumeric strings. So to do the task we use the Random class although it generates integers we can use them to create random strings. The Random class provides different types of methods to generate a random string. Random strings are generally used for captcha verification, etc.
Example:
Random String: ZDTXZFPYQEOUPGMEIYCEUSK

Random String: PSSR34YB
We can generate a random string using the Next() method. This method takes two arguments minimum and maximum range and returns a positive random integer within the specified minimum and maximum range.
Syntax:
public virtual int Next (int mValue, int nValue);
Here, mValue is the upper boundary of the random number generated, and nValue is the lower bound of the random number returned.
Approach:
1. Create a object of the Random class
2. Randomly choose the size of the string using the Next() method and store in stringlength variable.
3. Repeat the following steps stringlength times using for loop:
Randomly choose a number between 0 and 25
Add 65 to the random number and convert it to char using convert.ToChar() method
4. Display the output.
Example:
C#
// C# program to generate random stringsusing System;  class GFG{  static void Main(){      // Creating object of random class    Random rand = new Random();      // Choosing the size of string    // Using Next() string    int stringlen = rand.Next(4, 10);    int randValue;    string str = "";    char letter;    for (int i = 0; i < stringlen; i++)    {          // Generating a random number.        randValue = rand.Next(0, 26);          // Generating random character by converting        // the random number into character.        letter = Convert.ToChar(randValue + 65);          // Appending the letter to string.        str = str + letter;    }    Console.Write("Random String:" + str);}}
Output:
Random String:UUYXBGA
Explanation: In the above example, we will generate a random number between 0 and 25 and add it to 65, then it will become the ASCII value of alphabets. The ASCII value is converted into character using the ToChar() method. This entire step will be repeated multiple times using for loop and a string is formed by appending all the randomly generated characters.
We can also generate random strings using this method. In this method, we pass a string that contains 26 alphabets. Then from the 26 alphabets, we will select a letter randomly and append it to the string, by repeating this a random string is formed.
Approach:
Initialize a string with alphabets i.e. str=“abc.......xyz”Initialize an empty string and name it as “ran”.Choose the size of the string to be generated.Now using Next() method generate a random number and select the character at that index in the alphabet string.Append that character to randomString.Repeat steps 4 and 5 for n time where n is the length of the string.
Initialize a string with alphabets i.e. str=“abc.......xyz”
Initialize an empty string and name it as “ran”.
Choose the size of the string to be generated.
Now using Next() method generate a random number and select the character at that index in the alphabet string.
Append that character to randomString.
Repeat steps 4 and 5 for n time where n is the length of the string.
Example:
C#
// C# program to generate random stringsusing System;  class GFG{  public static void Main(string[] args){    Random res = new Random();      // String of alphabets     String str = "abcdefghijklmnopqrstuvwxyz";    int size = 10;      // Initializing the empty string    String ran = "";      for (int i = 0; i < size; i++)    {          // Selecting a index randomly        int x = res.Next(26);          // Appending the character at the         // index to the random string.        ran = ran + str[x];    }      Console.WriteLine("Random String:" + ran);}}
Output:
Random String:mphhzgvpjr
Explanation: In this example, we create an object of the Random class. Then we store 26 alphabets in a string named “str”. Now we create a variable named “size” of integer type which represents the total number of characters present in the randomly generated string. Now we create an empty string named “ran”. Then we create a for loop that iterates till “i  < size” and inside this for loop we use the Next() method. This method generates random numbers less than 26, so we use these numbers as a position indicator to get the character from that position. So every time when the loop iterate we will get a random character. And in the end, we will append these characters and get a random string.
Alphanumeric strings are those strings that contain both alphabets and numbers. We can generate random alphanumeric strings using the above method.
Approach:
Initialize a string with both alphabets and numbers i.e. str = “abc.......xyz012....789”Initialize an empty string and name it as “randomString”.Choose the size of the string to be generated.Now using Next() method generate a random number and select the character at that index in the alphanumeric string.Append that character to randomString.Repeat steps 4 and 5 for n time where n is the length of the string.
Initialize a string with both alphabets and numbers i.e. str = “abc.......xyz012....789”
Initialize an empty string and name it as “randomString”.
Choose the size of the string to be generated.
Now using Next() method generate a random number and select the character at that index in the alphanumeric string.
Append that character to randomString.
Repeat steps 4 and 5 for n time where n is the length of the string.
Example:
C#
// C# program to generate random alphanumeric stringsusing System;  class GFG{  public static void Main(string[] args){    Random res = new Random();      // String that contain both alphabets and numbers    String str = "abcdefghijklmnopqrstuvwxyz0123456789";    int size = 8;      // Initializing the empty string    String randomstring = "";      for (int i = 0; i < size; i++)    {          // Selecting a index randomly        int x = res.Next(str.Length);          // Appending the character at the         // index to the random alphanumeric string.        randomstring = randomstring + str[x];    }      Console.WriteLine("Random alphanumeric String:" + randomstring);}}
Output:
Random alphanumeric String:v91d2p48
Explanation: In this example, we create an object of the Random class. Then we store both alphabets and numbers in a string named “str”. Now we create a variable named “size” of integer type which represents the total number of characters present in the randomly generated alphanumeric string. Now we create an empty string named “randomstring”. Then we create a for loop that iterates till “i  < size” and inside this for loop we use the Next() method. This method generates random numbers less than str.Length, so we use these numbers as a position indicator to get the character from that position. So every time when the loop iterate we will get a random character. And in the end, we will append these characters and get a random alphanumeric string.
 
gulshankumarar231
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C#