How to create random X-length string that contains letters and numbers. My fast solution is:
Guid.NewGuid().ToString("N").Substring(X);
Any another better ideas?
How to create random X-length string that contains letters and numbers. My fast solution is:
Guid.NewGuid().ToString("N").Substring(X);
Any another better ideas?
GUIDs are not random, they are unique! If you are using them where randomness is required, you are doing something very wrong.
There are several options for random data generation, but the question here is: what is it meant for? Rolling dice? Encrypting state secrets?
If you want "random" strings for dictionary keys, simply use a Guid
. They will be unique and more than adequate for keying dictionaries.
Warning, coded it and ran it once - otherwise untested. Performance versus your current solution is unquantified. Also, this implementation is a lot wordier than the answer linked in the question comments.
static void Main(string[] args)
{
Random r = new Random();
int x = r.Next(1, 1000);
char[] pool = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
char[] word = new char[x];
for (int i = 0; i < x; i++)
{
// max value is not inclusive, so no -1 from length.
int a = r.Next(pool.Length);
word[i] = pool[a];
}
Console.WriteLine(new string(word));
Console.ReadLine();
}
There's probably a nicer way to do this using the ASCII codes, but meh.
I once made a "random" password generator and it looked like this. You can modify it as you please, and there's probably some room for linq expressions here.
public static string GeneratePassWord(bool useNumbers,bool useLetters, bool useUpperAndLowerCase, bool useSpecialCharacters, int passwordLength)
{
Random randomNumber = new Random();
List<char> chars = new List<char>();
if (useNumbers) // Add numbers
{
for (int i = 0; i <= 9; i++)
{
chars.Add((char)(48 + i));
}
}
if (useLetters) // Add letters
{
for (int i = 0; i <= 25; i++) // Small letters
{
chars.Add((char)(97 + i));
}
if (useUpperAndLowerCase)
{
for (int i = 0; i <= 25; i++) // Large letters
{
chars.Add((char)(65 + i));
}
}
}
if (useSpecialCharacters) // Add specials
{
chars.Add((char)'!');
chars.Add((char)'#');
chars.Add((char)'%');
chars.Add((char)'&');
chars.Add((char)'_');
chars.Add((char)'.');
chars.Add((char)'+');
chars.Add((char)'@');
chars.Add((char)'$');
}
// Generate random password from char
if (chars.Count > 0)
{
StringBuilder newPass = new StringBuilder();
for (int i = 0; i <= passwordLength; i++)
{
newPass.Append(chars[randomNumber.Next(chars.Count)]);
}
return newPass.ToString();
}
else
{
return string.Empty;
}
}
As you see, it basically creates a List<> of chars, and then picks randomly from the list for each number of characters you want.