Pick random char

前端 未结 11 1455
名媛妹妹
名媛妹妹 2021-01-03 20:57

i have some chars:

chars = \"$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&\".ToCharArray();

now i\'m lookin

11条回答
  •  别那么骄傲
    2021-01-03 21:31

    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).

提交回复
热议问题