i have some chars:
chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
now i'm looking for a method to return a random char from these.
I found a code which maybe can be usefull:
static Random random = new Random();
public static char GetLetter()
{
// This method returns a random lowercase letter
// ... Between 'a' and 'z' inclusize.
int num = random.Next(0, 26); // Zero to 25
char let = (char)('a' + num);
return let;
}
this code returns me a random char form the alphabet but only returns me lower case letters
I had approximate issue and I did it by this way:
Well you're nearly there - you want to return a random element from a string, so you just generate a random number in the range of the length of the string:
I'd advise against using a
static
variable of typeRandom
without any locking, by the way -Random
isn't thread-safe. See my article on random numbers for more details (and workarounds).Instead of 26 please use size of your CHARS buffer.
Then instead of
use
You can use it like;
Here is a
DEMO
.I'm not sure how efficient it is as I'm very new to coding, however, why not just utilize the random number your already creating? Wouldn't this "randomize" an uppercase char as well?
Also, if you're looking to take a single letter from your char[], would it be easier to just use a string?