选择随机字符 [英] Pick random char
问题描述
我有一些字符:
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
推荐答案
好了,你几乎要从字符串返回一个随机元素,所以你只是生成一个随机number在字符串长度范围内:
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];
}
我建议 使用 static
类型的变量随机
没有任何锁定,顺便 - 随机
不是线程安全的。有关详情(和解决方法),请参阅我的随机数字。
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).
这篇关于选择随机字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!