I found this snippet of code that generates a string of random characters.
But is there a more elegant/faster/more reliable way to do this? This seems to rely on the fact that the numbers 26-91 are valid characters given the current encoding.
/// <summary>
/// Generates a random string with the given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <param name="lowerCase">If true, generate lowercase string</param>
/// <returns>Random string</returns>
private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for(int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if(lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.
We can Generate Random Strings and Passwords in Python using secrets. choice(). For Cryptographically more secure random numbers, this function of the secret module can be used as its internal algorithm is framed in a way to generate less predictable random numbers.
Use math/rand to Generate Random String of Fixed Length in Golang. Go's math/rand package provides pseudorandom number generation. We'll use the package in this example and pass a random string to receive the output of a fixed-length string.
Using this random module, different random strings can be generated. random. choice() is used to generate strings in which characters may repeat, while random. sample() is used for non-repeating characters.
I'd prefer to pass the Random
instance into the method - then you can reuse the same instance multiple times, which is important if you need to generate lots of random strings in quick succession. However, I'd also modify it somewhat anyway:
public const string LowerCaseAlphabet = "abcdefghijklmnopqrstuvwyxz";
public const string UpperCaseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static string GenerateUpperCaseString(int size, Random rng)
{
return GenerateString(size, rng, UpperCaseAlphabet);
}
public static string GenerateLowerCaseString(int size, Random rng)
{
return GenerateString(size, rng, LowerCaseAlphabet);
}
public static string GenerateString(int size, Random rng, string alphabet)
{
char[] chars = new char[size];
for (int i=0; i < size; i++)
{
chars[i] = alphabet[rng.Next(alphabet.Length)];
}
return new string(chars);
}
Random.NextDouble()
indicates a lack of knowledge of the Random class. (In particular Random.Next(int, int)
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