I want to generate a random list of strings containing only alphanumeric characters. The length of the string can be of any size. Is there any way to do this using recursion?
Since you explicitly asked for recursion, here is a recursive solution. It’s very slow, though.
static string allowedCharacters = "abcdefghijklmnopqrstuvwxyz0123456789";
static Random rnd = new Random();
static string randomString(int length)
{
if (length == 0)
return "";
return allowedCharacters[rnd.Next(0, allowedCharacters.Length)]
+ randomString(length - 1); // This is the recursive call.
}
Now you can use this to generate a string of a random length:
// Outputs a random string of a length between 5 and 49 characters
Console.WriteLine(randomString(rnd.Next(5, 50)));
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