Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random char

Tags:

c#

random

char

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


1 Answers

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:

public static char GetRandomCharacter(string text, Random rng)
{
    int index = rng.Next(text.Length);
    return text[index];
}

I'd advise against using a static variable of type Random without any locking, by the way - Random isn't thread-safe. See my article on random numbers for more details (and workarounds).

like image 188
Jon Skeet Avatar answered Sep 09 '25 00:09

Jon Skeet