Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate random alphanumeric strings?

Tags:

c#

.net

random

How can I generate a random 8 character alphanumeric string in C#?

like image 561
KingNestor Avatar asked Aug 27 '09 23:08

KingNestor


People also ask

How do you generate random unique alphanumeric strings?

There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.

How do you generate random alphanumeric strings in C++?

Example 1: Using the rand() Function to Generate Random Alphabets in C++ The following C++ program generates a random string alphabet by using rand() function and srand() function. The rand() function generates the random alphabets in a string and srand() function is used to seed the rand() function.

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .


2 Answers

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var stringChars = new char[8]; var random = new Random();  for (int i = 0; i < stringChars.Length; i++) {     stringChars[i] = chars[random.Next(chars.Length)]; }  var finalString = new String(stringChars); 

Not as elegant as the Linq solution.

(Note: The use of the Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)

like image 28
Dan Rigby Avatar answered Nov 26 '22 08:11

Dan Rigby


I heard LINQ is the new black, so here's my attempt using LINQ:

private static Random random = new Random();  public static string RandomString(int length) {     const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";     return new string(Enumerable.Repeat(chars, length)         .Select(s => s[random.Next(s.Length)]).ToArray()); } 

(Note: The use of the Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)

like image 196
dtb Avatar answered Nov 26 '22 08:11

dtb