我需要生成一个包含空格和mixedCase的随机字符串.
这就是我到目前为止所做的一切:
////// The Typing monkey generates random strings - can't be static 'cause it's a monkey. /// ////// If you wait long enough it will eventually produce Shakespeare. /// class TypingMonkey { ////// The Typing Monkey Generates a random string with the given length. /// /// Size of the string ///Random string public string TypeAway(int size) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } return builder.ToString(); } }
我只得到没有空格的大写字符串 - 我相信调整应该非常严格,以便在汤中混合大小写和空格.
任何帮助非常感谢!
最简单的方法是简单地创建一个包含以下值的字符串:
private readonly string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
然后使用RNG访问此字符串中的随机元素:
public string TypeAway(int size) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = legalCharacters[random.Next(0, legalCharacters.Length)]; builder.Append(ch); } return builder.ToString(); }