How can I generate a random 8 character alphanumeric string in C#?
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.
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.
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 .
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.)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With